autoagents-core 0.4.0

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

use crate::agent::constants::DEFAULT_CHANNEL_BUFFER;

use crate::channel::{Receiver, Sender, channel};

#[cfg(not(target_arch = "wasm32"))]
use crate::event_fanout::EventFanout;
use crate::utils::{BoxEventStream, receiver_into_stream};
#[cfg(not(target_arch = "wasm32"))]
use futures_util::stream;

/// Marker type for direct (non-actor) agents.
///
/// Direct agents execute immediately within the caller's task without
/// requiring a runtime or event wiring. Use this for simple one-shot
/// invocations and unit tests.
#[derive(Clone, Copy)]
pub struct DirectAgent {}

impl AgentType for DirectAgent {
    fn type_name() -> &'static str {
        "direct_agent"
    }
}

/// Handle for a direct agent containing the agent instance and an event stream
/// receiver. Use `agent.run(...)` for one-shot calls or `agent.run_stream(...)`
/// to receive streaming outputs.
///
/// Terminal outcomes emit protocol events on [`Self::rx`]: `TaskComplete` on success
/// and `TaskError` on failure (hook abort, executor error, stream setup error,
/// in-stream item errors, and empty streams). For `run_stream()`, `TaskComplete`
/// is emitted when the returned output stream is fully drained; the last successful
/// item is used for the event payload.
pub struct DirectAgentHandle<T: AgentDeriveT + AgentExecutor + AgentHooks + Send + Sync> {
    pub agent: BaseAgent<T, DirectAgent>,
    pub rx: BoxEventStream<Event>,
    #[cfg(not(target_arch = "wasm32"))]
    fanout: Option<EventFanout>,
}

impl<T: AgentDeriveT + AgentExecutor + AgentHooks> DirectAgentHandle<T> {
    pub fn new(agent: BaseAgent<T, DirectAgent>, rx: BoxEventStream<Event>) -> Self {
        Self {
            agent,
            rx,
            #[cfg(not(target_arch = "wasm32"))]
            fanout: None,
        }
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub fn subscribe_events(&mut self) -> BoxEventStream<Event> {
        if let Some(fanout) = &self.fanout {
            return fanout.subscribe();
        }

        let stream = std::mem::replace(&mut self.rx, Box::pin(stream::empty::<Event>()));
        let fanout = EventFanout::new(stream, DEFAULT_CHANNEL_BUFFER);
        self.rx = fanout.subscribe();
        let stream = fanout.subscribe();
        self.fanout = Some(fanout);
        stream
    }
}

impl<T: AgentDeriveT + AgentExecutor + AgentHooks> AgentBuilder<T, DirectAgent> {
    /// Build the BaseAgent and return a wrapper
    #[allow(clippy::result_large_err)]
    pub async fn build(self) -> Result<DirectAgentHandle<T>, Error> {
        let llm = self.llm.ok_or(AgentBuildError::BuildFailure(
            "LLM provider is required".to_string(),
        ))?;
        let (tx, rx): (Sender<Event>, Receiver<Event>) = channel(DEFAULT_CHANNEL_BUFFER);
        let agent: BaseAgent<T, DirectAgent> =
            BaseAgent::<T, DirectAgent>::new(self.inner, llm, self.memory, tx, self.stream).await?;
        let stream = receiver_into_stream(rx);
        Ok(DirectAgentHandle::new(agent, stream))
    }
}

fn wrap_direct_stream_with_terminal_events<T>(
    agent: BaseAgent<T, DirectAgent>,
    stream: crate::utils::BoxRuntimeStream<
        Result<<T as AgentExecutor>::Output, <T as AgentExecutor>::Error>,
    >,
    task: Task,
    context: Arc<Context>,
    tx_event: Option<crate::channel::Sender<Event>>,
    submission_id: autoagents_protocol::SubmissionId,
    actor_id: autoagents_protocol::ActorID,
) -> crate::utils::BoxRuntimeStream<Result<<T as AgentDeriveT>::Output, Error>>
where
    T: AgentDeriveT + AgentExecutor + AgentHooks + Send + Sync,
    Value: From<<T as AgentExecutor>::Output>,
    <T as AgentDeriveT>::Output: From<<T as AgentExecutor>::Output>,
    <T as AgentExecutor>::Output: Clone,
    <T as AgentExecutor>::Error: Into<RunnableAgentError>,
{
    use futures::StreamExt;

    Box::pin(futures::stream::unfold(
        (
            stream,
            false,
            None::<<T as AgentExecutor>::Output>,
            task,
            context,
        ),
        move |(mut stream, mut saw_error, last, task, context)| {
            let agent = agent.clone_shallow();
            let tx_event = tx_event.clone();
            async move {
                match stream.next().await {
                    Some(result) => {
                        match EventHelper::map_executor_stream_item(
                            &tx_event,
                            submission_id,
                            actor_id,
                            result,
                        )
                        .await
                        {
                            Ok(output) => {
                                let agent_out: <T as AgentDeriveT>::Output = output.clone().into();
                                Some((
                                    Ok(agent_out),
                                    (stream, saw_error, Some(output), task, context),
                                ))
                            }
                            Err(err) => {
                                saw_error = true;
                                Some((
                                    Err(Error::from(err)),
                                    (stream, saw_error, last, task, context),
                                ))
                            }
                        }
                    }
                    None => {
                        if !saw_error {
                            if let Some(executor_out) = last {
                                let _ = agent
                                    .finish_executor_run(
                                        &task,
                                        context.as_ref(),
                                        submission_id,
                                        executor_out,
                                    )
                                    .await;
                            } else {
                                let err = RunnableAgentError::ExecutorError(
                                    "Stream completed without output".to_string(),
                                );
                                #[cfg(not(target_arch = "wasm32"))]
                                EventHelper::send_task_error(
                                    &tx_event,
                                    submission_id,
                                    actor_id,
                                    err.to_string(),
                                )
                                .await;
                            }
                        }
                        None
                    }
                }
            }
        },
    ))
}

impl<T: AgentDeriveT + AgentExecutor + AgentHooks> BaseAgent<T, DirectAgent> {
    /// Execute the agent for a single task and return the final agent output.
    pub async fn run(&self, task: Task) -> Result<<T as AgentDeriveT>::Output, RunnableAgentError>
    where
        Value: From<<T as AgentExecutor>::Output>,
        <T as AgentDeriveT>::Output: From<<T as AgentExecutor>::Output>,
        <T as AgentExecutor>::Output: Clone,
        <T as AgentExecutor>::Error: Into<RunnableAgentError>,
    {
        let submission_id = task.submission_id;
        let tx_event = self.tx.clone();
        let context = self.create_context();

        //Run Hook
        let hook_outcome = self.inner.on_run_start(&task, &context).await;
        match hook_outcome {
            HookOutcome::Abort => {
                return Err(
                    EventHelper::abort_run_from_hook(&tx_event, submission_id, self.id).await,
                );
            }
            HookOutcome::Continue => {}
        }

        // Execute the agent's logic using the executor
        match self.inner().execute(&task, context.clone()).await {
            Ok(output) => {
                self.finish_executor_run(&task, &context, submission_id, output)
                    .await
            }
            Err(e) => {
                let err: RunnableAgentError = e.into();
                #[cfg(not(target_arch = "wasm32"))]
                EventHelper::send_task_error(&tx_event, submission_id, self.id, err.to_string())
                    .await;
                Err(err)
            }
        }
    }

    /// Execute the agent with streaming enabled and receive a stream of
    /// partial outputs which culminate in a final chunk with `done=true`.
    pub async fn run_stream(
        &self,
        task: Task,
    ) -> Result<
        crate::utils::BoxRuntimeStream<Result<<T as AgentDeriveT>::Output, Error>>,
        RunnableAgentError,
    >
    where
        Value: From<<T as AgentExecutor>::Output>,
        <T as AgentDeriveT>::Output: From<<T as AgentExecutor>::Output>,
        <T as AgentExecutor>::Output: Clone,
        <T as AgentExecutor>::Error: Into<RunnableAgentError>,
    {
        let submission_id = task.submission_id;
        let tx_event = self.tx.clone();
        let context = self.create_context();

        //Run Hook
        let hook_outcome = self.inner.on_run_start(&task, &context).await;
        match hook_outcome {
            HookOutcome::Abort => {
                return Err(
                    EventHelper::abort_run_from_hook(&tx_event, submission_id, self.id).await,
                );
            }
            HookOutcome::Continue => {}
        }

        // Execute the agent's streaming logic using the executor
        match self.inner().execute_stream(&task, context.clone()).await {
            Ok(stream) => Ok(wrap_direct_stream_with_terminal_events(
                self.clone_shallow(),
                stream,
                task,
                context,
                tx_event,
                submission_id,
                self.id,
            )),
            Err(e) => {
                let err: RunnableAgentError = e.into();
                #[cfg(not(target_arch = "wasm32"))]
                EventHelper::send_task_error(&tx_event, submission_id, self.id, err.to_string())
                    .await;
                Err(err)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::hooks::HookOutcome;
    use crate::agent::output::AgentOutputT;
    use crate::agent::prebuilt::executor::{
        BasicAgent as StableBasicAgent, BasicAgentOutput, ReActAgent as StableReActAgent,
        ReActAgentOutput,
    };
    use crate::agent::task::Task;
    use crate::agent::{Context, ExecutorConfig};
    use crate::tests::{
        ConfigurableLLMProvider, MockAgentImpl, MultiItemStreamAgent, TestAgentOutput, TestError,
    };
    use crate::tool::ToolT;
    use async_trait::async_trait;
    use futures::StreamExt;
    use serde::{Deserialize, Serialize};
    use serde_json::Value;
    use std::sync::{
        Arc,
        atomic::{AtomicBool, AtomicUsize, Ordering},
    };

    #[tokio::test]
    async fn test_direct_agent_build_requires_llm() {
        let mock_agent = MockAgentImpl::new("direct", "direct agent");
        let err = match AgentBuilder::<_, DirectAgent>::new(mock_agent)
            .build()
            .await
        {
            Ok(_) => panic!("expected missing llm error"),
            Err(err) => err,
        };

        assert!(matches!(err, crate::error::Error::AgentBuildError(_)));
    }

    #[tokio::test]
    async fn test_direct_agent_run_success() {
        let mock_agent = MockAgentImpl::new("direct", "direct agent");
        let llm = Arc::new(ConfigurableLLMProvider::default());
        let mut handle = AgentBuilder::<_, DirectAgent>::new(mock_agent)
            .llm(llm)
            .build()
            .await
            .expect("build should succeed");

        let task = Task::new("hello");
        let result = handle.agent.run(task).await.expect("run should succeed");
        assert_eq!(result.result, "Processed: hello");

        let event = tokio::time::timeout(std::time::Duration::from_secs(1), handle.rx.next())
            .await
            .expect("timed out waiting for TaskComplete event")
            .expect("stream ended without event");
        match event {
            Event::TaskComplete { result, .. } => {
                let parsed: Value =
                    serde_json::from_str(&result).expect("TaskComplete result should be JSON");
                assert_eq!(parsed["result"], "Processed: hello");
            }
            other => panic!("expected TaskComplete, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_direct_agent_run_executor_error() {
        let mock_agent = MockAgentImpl::new("direct", "direct agent").with_failure(true);
        let llm = Arc::new(ConfigurableLLMProvider::default());
        let mut handle = AgentBuilder::<_, DirectAgent>::new(mock_agent)
            .llm(llm)
            .build()
            .await
            .expect("build should succeed");

        let task = Task::new("fail");
        let err = handle.agent.run(task).await.expect_err("expected error");
        assert!(matches!(err, RunnableAgentError::ExecutorError(_)));

        let event = tokio::time::timeout(std::time::Duration::from_secs(1), handle.rx.next())
            .await
            .expect("timed out waiting for TaskError event")
            .expect("stream ended without event");
        match event {
            Event::TaskError { error, .. } => {
                assert!(error.contains("Mock execution failed"));
            }
            other => panic!("expected TaskError, got {other:?}"),
        }
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    struct HookCountOutput {
        result: String,
    }

    impl AgentOutputT for HookCountOutput {
        fn output_schema() -> &'static str {
            r#"{"type":"object","properties":{"result":{"type":"string"}},"required":["result"]}"#
        }

        fn structured_output_format() -> Value {
            serde_json::json!({
                "name": "HookCountOutput",
                "description": "Hook count output",
                "schema": {
                    "type": "object",
                    "properties": {
                        "result": {"type": "string"}
                    },
                    "required": ["result"]
                },
                "strict": true
            })
        }
    }

    impl From<BasicAgentOutput> for HookCountOutput {
        fn from(output: BasicAgentOutput) -> Self {
            Self {
                result: output.response,
            }
        }
    }

    impl From<ReActAgentOutput> for HookCountOutput {
        fn from(output: ReActAgentOutput) -> Self {
            Self {
                result: output.response,
            }
        }
    }

    #[derive(Debug, Clone)]
    struct CountingHookAgent {
        on_run_start_calls: Arc<AtomicUsize>,
    }

    #[async_trait]
    impl AgentDeriveT for CountingHookAgent {
        type Output = HookCountOutput;

        fn description(&self) -> &'static str {
            "counting hook agent"
        }

        fn output_schema(&self) -> Option<Value> {
            Some(serde_json::json!({
                "type": "object",
                "properties": {"result": {"type": "string"}},
                "required": ["result"]
            }))
        }

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

        fn tools(&self) -> Vec<Box<dyn ToolT>> {
            vec![]
        }
    }

    #[async_trait]
    impl AgentHooks for CountingHookAgent {
        async fn on_run_start(&self, _task: &Task, _ctx: &Context) -> HookOutcome {
            self.on_run_start_calls.fetch_add(1, Ordering::SeqCst);
            HookOutcome::Continue
        }
    }

    #[tokio::test]
    async fn test_direct_basic_agent_run_calls_on_run_start_once() {
        let calls = Arc::new(AtomicUsize::new(0));
        let llm = Arc::new(ConfigurableLLMProvider::default());
        let handle =
            AgentBuilder::<_, DirectAgent>::new(StableBasicAgent::new(CountingHookAgent {
                on_run_start_calls: Arc::clone(&calls),
            }))
            .llm(llm)
            .build()
            .await
            .expect("build should succeed");

        let task = Task::new("hello");
        let result = handle.agent.run(task).await.expect("run should succeed");

        assert_eq!(result.result, "Mock response");
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn test_direct_react_agent_run_calls_on_run_start_once() {
        let calls = Arc::new(AtomicUsize::new(0));
        let llm = Arc::new(ConfigurableLLMProvider::default());
        let handle =
            AgentBuilder::<_, DirectAgent>::new(StableReActAgent::new(CountingHookAgent {
                on_run_start_calls: Arc::clone(&calls),
            }))
            .llm(llm)
            .build()
            .await
            .expect("build should succeed");

        let task = Task::new("hello");
        let result = handle.agent.run(task).await.expect("run should succeed");

        assert_eq!(result.result, "Mock response");
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[derive(Clone, Debug)]
    struct StreamAgent;

    #[async_trait]
    impl AgentDeriveT for StreamAgent {
        type Output = TestAgentOutput;

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

        fn output_schema(&self) -> Option<Value> {
            Some(TestAgentOutput::structured_output_format())
        }

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

        fn tools(&self) -> Vec<Box<dyn ToolT>> {
            vec![]
        }
    }

    #[async_trait]
    impl AgentExecutor for StreamAgent {
        type Output = TestAgentOutput;
        type Error = TestError;

        fn config(&self) -> ExecutorConfig {
            ExecutorConfig::default()
        }

        async fn execute(
            &self,
            task: &Task,
            _context: Arc<Context>,
        ) -> Result<Self::Output, Self::Error> {
            Ok(TestAgentOutput {
                result: format!("Streamed: {}", task.prompt),
            })
        }
    }

    impl AgentHooks for StreamAgent {}

    #[tokio::test]
    async fn test_direct_agent_run_stream_default_executes_once() {
        let llm = Arc::new(ConfigurableLLMProvider::default());
        let mut handle = AgentBuilder::<_, DirectAgent>::new(StreamAgent)
            .llm(llm)
            .build()
            .await
            .expect("build should succeed");

        let task = Task::new("stream");
        let stream = handle
            .agent
            .run_stream(task)
            .await
            .expect("stream should succeed");
        let outputs: Vec<_> = stream.collect().await;
        assert_eq!(outputs.len(), 1);
        let output = outputs[0].as_ref().expect("expected Ok output");
        assert_eq!(output.result, "Streamed: stream");

        let event = tokio::time::timeout(std::time::Duration::from_secs(1), handle.rx.next())
            .await
            .expect("timed out waiting for TaskComplete event")
            .expect("stream ended without event");
        match event {
            Event::TaskComplete { result, .. } => {
                let parsed: Value =
                    serde_json::from_str(&result).expect("TaskComplete result should be JSON");
                assert_eq!(parsed["result"], "Streamed: stream");
            }
            other => panic!("expected TaskComplete, got {other:?}"),
        }
    }

    #[derive(Debug)]
    struct AbortAgent {
        executed: Arc<AtomicBool>,
    }

    #[async_trait]
    impl AgentDeriveT for AbortAgent {
        type Output = TestAgentOutput;

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

        fn output_schema(&self) -> Option<Value> {
            Some(TestAgentOutput::structured_output_format())
        }

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

        fn tools(&self) -> Vec<Box<dyn ToolT>> {
            vec![]
        }
    }

    #[async_trait]
    impl AgentExecutor for AbortAgent {
        type Output = TestAgentOutput;
        type Error = TestError;

        fn config(&self) -> ExecutorConfig {
            ExecutorConfig::default()
        }

        async fn execute(
            &self,
            _task: &Task,
            _context: Arc<Context>,
        ) -> Result<Self::Output, Self::Error> {
            self.executed.store(true, Ordering::SeqCst);
            Ok(TestAgentOutput {
                result: "should-not-run".to_string(),
            })
        }
    }

    #[async_trait]
    impl AgentHooks for AbortAgent {
        async fn on_run_start(&self, _task: &Task, _ctx: &Context) -> HookOutcome {
            HookOutcome::Abort
        }
    }

    #[tokio::test]
    async fn test_direct_agent_run_aborts_before_execute() {
        let executed = Arc::new(AtomicBool::new(false));
        let agent = AbortAgent {
            executed: Arc::clone(&executed),
        };
        let llm = Arc::new(ConfigurableLLMProvider::default());
        let mut handle = AgentBuilder::<_, DirectAgent>::new(agent)
            .llm(llm)
            .build()
            .await
            .expect("build should succeed");

        let task = Task::new("abort");
        let err = handle.agent.run(task).await.expect_err("expected abort");
        assert!(matches!(err, RunnableAgentError::Abort));
        assert!(!executed.load(Ordering::SeqCst));

        let event = tokio::time::timeout(std::time::Duration::from_secs(1), handle.rx.next())
            .await
            .expect("timed out waiting for TaskError event")
            .expect("stream ended without event");
        match event {
            Event::TaskError { error, .. } => {
                assert!(error.contains("Abort"));
            }
            other => panic!("expected TaskError, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_direct_agent_run_stream_aborts_before_execute_stream() {
        let executed = Arc::new(AtomicBool::new(false));
        let agent = AbortAgent {
            executed: Arc::clone(&executed),
        };
        let llm = Arc::new(ConfigurableLLMProvider::default());
        let mut handle = AgentBuilder::<_, DirectAgent>::new(agent)
            .llm(llm)
            .stream(true)
            .build()
            .await
            .expect("build should succeed");

        let task = Task::new("abort");
        let err = match handle.agent.run_stream(task).await {
            Err(err) => err,
            Ok(_) => panic!("expected abort"),
        };
        assert!(matches!(err, RunnableAgentError::Abort));
        assert!(!executed.load(Ordering::SeqCst));

        let event = tokio::time::timeout(std::time::Duration::from_secs(1), handle.rx.next())
            .await
            .expect("timed out waiting for TaskError event")
            .expect("stream ended without event");
        match event {
            Event::TaskError { error, .. } => {
                assert!(error.contains("Abort"));
            }
            other => panic!("expected TaskError, got {other:?}"),
        }
    }

    #[derive(Debug, Clone)]
    struct FailingStreamSetupAgent;

    #[async_trait]
    impl AgentDeriveT for FailingStreamSetupAgent {
        type Output = TestAgentOutput;

        fn description(&self) -> &'static str {
            "failing stream setup"
        }

        fn output_schema(&self) -> Option<Value> {
            Some(TestAgentOutput::structured_output_format())
        }

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

        fn tools(&self) -> Vec<Box<dyn ToolT>> {
            vec![]
        }
    }

    #[async_trait]
    impl AgentExecutor for FailingStreamSetupAgent {
        type Output = TestAgentOutput;
        type Error = TestError;

        fn config(&self) -> ExecutorConfig {
            ExecutorConfig::default()
        }

        async fn execute(
            &self,
            _task: &Task,
            _context: Arc<Context>,
        ) -> Result<Self::Output, Self::Error> {
            Ok(TestAgentOutput {
                result: "unused".to_string(),
            })
        }

        async fn execute_stream(
            &self,
            _task: &Task,
            _context: Arc<Context>,
        ) -> Result<crate::utils::BoxRuntimeStream<Result<Self::Output, Self::Error>>, Self::Error>
        {
            Err(TestError::ExecutionFailed(
                "stream setup failed".to_string(),
            ))
        }
    }

    impl AgentHooks for FailingStreamSetupAgent {}

    #[tokio::test]
    async fn test_direct_agent_run_stream_setup_error_emits_task_error() {
        let llm = Arc::new(ConfigurableLLMProvider::default());
        let mut handle = AgentBuilder::<_, DirectAgent>::new(FailingStreamSetupAgent)
            .llm(llm)
            .stream(true)
            .build()
            .await
            .expect("build should succeed");

        let err = match handle.agent.run_stream(Task::new("fail setup")).await {
            Err(err) => err,
            Ok(_) => panic!("expected stream setup failure"),
        };
        assert!(matches!(err, RunnableAgentError::ExecutorError(_)));

        let event = tokio::time::timeout(std::time::Duration::from_secs(1), handle.rx.next())
            .await
            .expect("timed out waiting for TaskError event")
            .expect("stream ended without event");
        match event {
            Event::TaskError { error, .. } => {
                assert!(error.contains("stream setup failed"));
            }
            other => panic!("expected TaskError, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_direct_agent_run_stream_item_error_emits_task_error() {
        let mock_agent = MockAgentImpl::new("direct", "direct agent").with_failure(true);
        let llm = Arc::new(ConfigurableLLMProvider::default());
        let mut handle = AgentBuilder::<_, DirectAgent>::new(mock_agent)
            .llm(llm)
            .stream(true)
            .build()
            .await
            .expect("build should succeed");

        let mut stream = handle
            .agent
            .run_stream(Task::new("fail"))
            .await
            .expect("default execute_stream should return Ok stream");

        let err = stream
            .next()
            .await
            .expect("stream should yield one item")
            .expect_err("expected stream item error");
        assert!(matches!(err, Error::RunnableAgentError(_)));

        let event = tokio::time::timeout(std::time::Duration::from_secs(1), handle.rx.next())
            .await
            .expect("timed out waiting for TaskError event")
            .expect("stream ended without event");
        match event {
            Event::TaskError { error, .. } => {
                assert!(error.contains("Mock execution failed"));
            }
            other => panic!("expected TaskError, got {other:?}"),
        }
    }

    #[derive(Debug, Clone)]
    struct StreamItemErrorAgent;

    #[async_trait]
    impl AgentDeriveT for StreamItemErrorAgent {
        type Output = TestAgentOutput;

        fn description(&self) -> &'static str {
            "stream item error agent"
        }

        fn output_schema(&self) -> Option<Value> {
            Some(TestAgentOutput::structured_output_format())
        }

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

        fn tools(&self) -> Vec<Box<dyn ToolT>> {
            vec![]
        }
    }

    #[async_trait]
    impl AgentExecutor for StreamItemErrorAgent {
        type Output = TestAgentOutput;
        type Error = TestError;

        fn config(&self) -> ExecutorConfig {
            ExecutorConfig::default()
        }

        async fn execute(
            &self,
            _task: &Task,
            _context: Arc<Context>,
        ) -> Result<Self::Output, Self::Error> {
            Ok(TestAgentOutput {
                result: "unused".to_string(),
            })
        }

        async fn execute_stream(
            &self,
            _task: &Task,
            _context: Arc<Context>,
        ) -> Result<crate::utils::BoxRuntimeStream<Result<Self::Output, Self::Error>>, Self::Error>
        {
            Ok(Box::pin(futures::stream::iter([Err(
                TestError::ExecutionFailed("stream item failed".to_string()),
            )])))
        }
    }

    impl AgentHooks for StreamItemErrorAgent {}

    #[tokio::test]
    async fn test_direct_agent_run_stream_custom_item_error_emits_task_error() {
        let llm = Arc::new(ConfigurableLLMProvider::default());
        let mut handle = AgentBuilder::<_, DirectAgent>::new(StreamItemErrorAgent)
            .llm(llm)
            .stream(true)
            .build()
            .await
            .expect("build should succeed");

        let mut stream = handle
            .agent
            .run_stream(Task::new("stream error"))
            .await
            .expect("stream should start");

        let err = stream
            .next()
            .await
            .expect("stream should yield one item")
            .expect_err("expected stream item failure");
        assert!(matches!(err, Error::RunnableAgentError(_)));

        let event = tokio::time::timeout(std::time::Duration::from_secs(1), handle.rx.next())
            .await
            .expect("timed out waiting for TaskError event")
            .expect("stream ended without event");
        match event {
            Event::TaskError { error, .. } => {
                assert!(error.contains("stream item failed"));
            }
            other => panic!("expected TaskError, got {other:?}"),
        }
    }

    #[derive(Debug, Clone)]
    struct EmptyStreamAgent;

    #[async_trait]
    impl AgentDeriveT for EmptyStreamAgent {
        type Output = TestAgentOutput;

        fn description(&self) -> &'static str {
            "empty stream agent"
        }

        fn output_schema(&self) -> Option<Value> {
            Some(TestAgentOutput::structured_output_format())
        }

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

        fn tools(&self) -> Vec<Box<dyn ToolT>> {
            vec![]
        }
    }

    #[async_trait]
    impl AgentExecutor for EmptyStreamAgent {
        type Output = TestAgentOutput;
        type Error = TestError;

        fn config(&self) -> ExecutorConfig {
            ExecutorConfig::default()
        }

        async fn execute(
            &self,
            _task: &Task,
            _context: Arc<Context>,
        ) -> Result<Self::Output, Self::Error> {
            Ok(TestAgentOutput {
                result: "unused".to_string(),
            })
        }

        async fn execute_stream(
            &self,
            _task: &Task,
            _context: Arc<Context>,
        ) -> Result<crate::utils::BoxRuntimeStream<Result<Self::Output, Self::Error>>, Self::Error>
        {
            Ok(Box::pin(futures::stream::empty()))
        }
    }

    impl AgentHooks for EmptyStreamAgent {}

    #[tokio::test]
    async fn test_direct_agent_run_stream_empty_stream_emits_task_error() {
        let llm = Arc::new(ConfigurableLLMProvider::default());
        let mut handle = AgentBuilder::<_, DirectAgent>::new(EmptyStreamAgent)
            .llm(llm)
            .stream(true)
            .build()
            .await
            .expect("build should succeed");

        let stream = handle
            .agent
            .run_stream(Task::new("empty"))
            .await
            .expect("stream should start");
        let outputs: Vec<_> = stream.collect().await;
        assert!(outputs.is_empty());

        let event = tokio::time::timeout(std::time::Duration::from_secs(1), handle.rx.next())
            .await
            .expect("timed out waiting for TaskError event")
            .expect("stream ended without event");
        match event {
            Event::TaskError { error, .. } => {
                assert!(error.contains("without output"));
            }
            other => panic!("expected TaskError, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_direct_agent_run_stream_uses_last_item_for_task_complete() {
        let llm = Arc::new(ConfigurableLLMProvider::default());
        let mut handle = AgentBuilder::<_, DirectAgent>::new(MultiItemStreamAgent)
            .llm(llm)
            .stream(true)
            .build()
            .await
            .expect("build should succeed");

        let stream = handle
            .agent
            .run_stream(Task::new("chunked"))
            .await
            .expect("stream should start");
        let outputs: Vec<_> = stream.collect().await;
        assert_eq!(outputs.len(), 3);
        assert_eq!(outputs[2].as_ref().expect("third item").result, "chunked-3");

        let event = tokio::time::timeout(std::time::Duration::from_secs(1), handle.rx.next())
            .await
            .expect("timed out waiting for TaskComplete event")
            .expect("stream ended without event");
        match event {
            Event::TaskComplete { result, .. } => {
                let parsed: Value =
                    serde_json::from_str(&result).expect("TaskComplete result should be JSON");
                assert_eq!(parsed["sequence"], 3);
                assert_eq!(parsed["response"], "chunked-3");
            }
            other => panic!("expected TaskComplete, got {other:?}"),
        }
    }

    #[derive(Debug, Clone)]
    struct OkThenErrStreamAgent;

    #[async_trait]
    impl AgentDeriveT for OkThenErrStreamAgent {
        type Output = TestAgentOutput;

        fn description(&self) -> &'static str {
            "ok then err stream agent"
        }

        fn output_schema(&self) -> Option<Value> {
            Some(TestAgentOutput::structured_output_format())
        }

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

        fn tools(&self) -> Vec<Box<dyn ToolT>> {
            vec![]
        }
    }

    #[async_trait]
    impl AgentExecutor for OkThenErrStreamAgent {
        type Output = TestAgentOutput;
        type Error = TestError;

        fn config(&self) -> ExecutorConfig {
            ExecutorConfig::default()
        }

        async fn execute(
            &self,
            _task: &Task,
            _context: Arc<Context>,
        ) -> Result<Self::Output, Self::Error> {
            Ok(TestAgentOutput {
                result: "unused".to_string(),
            })
        }

        async fn execute_stream(
            &self,
            _task: &Task,
            _context: Arc<Context>,
        ) -> Result<crate::utils::BoxRuntimeStream<Result<Self::Output, Self::Error>>, Self::Error>
        {
            Ok(Box::pin(futures::stream::iter([
                Ok(TestAgentOutput {
                    result: "partial".to_string(),
                }),
                Err(TestError::ExecutionFailed("stream item failed".to_string())),
            ])))
        }
    }

    impl AgentHooks for OkThenErrStreamAgent {}

    #[tokio::test]
    async fn test_direct_agent_run_stream_ok_then_err_emits_task_error_not_task_complete() {
        let llm = Arc::new(ConfigurableLLMProvider::default());
        let mut handle = AgentBuilder::<_, DirectAgent>::new(OkThenErrStreamAgent)
            .llm(llm)
            .stream(true)
            .build()
            .await
            .expect("build should succeed");

        let mut stream = handle
            .agent
            .run_stream(Task::new("partial failure"))
            .await
            .expect("stream should start");

        let first = stream
            .next()
            .await
            .expect("stream should yield ok item")
            .expect("expected ok item");
        assert_eq!(first.result, "partial");

        let second = stream
            .next()
            .await
            .expect("stream should yield err item")
            .expect_err("expected err item");
        assert!(matches!(second, Error::RunnableAgentError(_)));

        assert!(
            stream.next().await.is_none(),
            "stream should end after error item"
        );

        let event = tokio::time::timeout(std::time::Duration::from_secs(1), handle.rx.next())
            .await
            .expect("timed out waiting for TaskError event")
            .expect("stream ended without event");
        match event {
            Event::TaskError { error, .. } => {
                assert!(error.contains("stream item failed"));
            }
            other => panic!("expected TaskError, got {other:?}"),
        }

        let no_terminal_success =
            tokio::time::timeout(std::time::Duration::from_millis(100), handle.rx.next()).await;
        assert!(
            no_terminal_success.is_err(),
            "Ok-then-Err stream should not emit TaskComplete after TaskError"
        );
    }
}