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

use crate::{Agent, ChatCompletionMessageFull, Conversation, ModelId, ToolCallFull, ToolResult};

/// A container for lifecycle events with agent and model ID context
///
/// This struct provides a consistent structure for all lifecycle events,
/// containing the agent and model ID along with event-specific payload data.
#[derive(Debug, PartialEq, Clone)]
pub struct EventData<P: Send + Sync> {
    /// The agent associated with this event
    pub agent: Agent,
    /// The model ID being used
    pub model_id: ModelId,
    /// Event-specific payload data
    pub payload: P,
}

impl<P: Send + Sync> EventData<P> {
    /// Creates a new event with the given agent, model ID, and payload
    pub fn new(agent: Agent, model_id: ModelId, payload: P) -> Self {
        Self { agent, model_id, payload }
    }
}

/// Payload for the Start event
#[derive(Debug, PartialEq, Clone, Default)]
pub struct StartPayload;

/// Payload for the End event
#[derive(Debug, PartialEq, Clone, Default)]
pub struct EndPayload;

/// Payload for the Request event
#[derive(Debug, PartialEq, Clone, Setters)]
#[setters(into)]
pub struct RequestPayload {
    /// The number of requests made
    pub request_count: usize,
}

impl RequestPayload {
    /// Creates a new request payload
    pub fn new(request_count: usize) -> Self {
        Self { request_count }
    }
}

/// Payload for the Response event
#[derive(Debug, PartialEq, Clone, Setters)]
#[setters(into)]
pub struct ResponsePayload {
    /// The full response message from the LLM
    pub message: ChatCompletionMessageFull,
}

impl ResponsePayload {
    /// Creates a new response payload
    pub fn new(message: ChatCompletionMessageFull) -> Self {
        Self { message }
    }
}

/// Payload for the ToolcallStart event
#[derive(Debug, PartialEq, Clone, Setters)]
#[setters(into)]
pub struct ToolcallStartPayload {
    /// The tool call details
    pub tool_call: ToolCallFull,
}

impl ToolcallStartPayload {
    /// Creates a new tool call start payload
    pub fn new(tool_call: ToolCallFull) -> Self {
        Self { tool_call }
    }
}

/// Payload for the ToolcallEnd event
#[derive(Debug, PartialEq, Clone, Setters)]
#[setters(into)]
pub struct ToolcallEndPayload {
    /// The original tool call that was executed
    pub tool_call: ToolCallFull,
    /// The tool result (success or failure)
    pub result: ToolResult,
}

impl ToolcallEndPayload {
    /// Creates a new tool call end payload
    pub fn new(tool_call: ToolCallFull, result: ToolResult) -> Self {
        Self { tool_call, result }
    }
}

/// Lifecycle events that can occur during conversation processing
#[derive(Debug, PartialEq, Clone, From)]
pub enum LifecycleEvent {
    /// Event fired when conversation processing starts
    Start(EventData<StartPayload>),

    /// Event fired when conversation processing ends
    End(EventData<EndPayload>),

    /// Event fired when a request is made to the LLM
    Request(EventData<RequestPayload>),

    /// Event fired when a response is received from the LLM
    Response(EventData<ResponsePayload>),

    /// Event fired when a tool call starts
    ToolcallStart(EventData<ToolcallStartPayload>),

    /// Event fired when a tool call ends
    ToolcallEnd(EventData<ToolcallEndPayload>),
}

/// Trait for handling lifecycle events
///
/// Implementations of this trait can be used to react to different
/// stages of conversation processing.
#[async_trait]
pub trait EventHandle<T: Send + Sync>: Send + Sync {
    /// Handles a lifecycle event and potentially modifies the conversation
    ///
    /// # Arguments
    /// * `event` - The lifecycle event that occurred
    /// * `conversation` - The current conversation state (mutable)
    ///
    /// # Errors
    /// Returns an error if the event handling fails
    async fn handle(&self, event: &T, conversation: &mut Conversation) -> anyhow::Result<()>;
}

/// Extension trait for combining event handlers
///
/// This trait provides methods to combine multiple event handlers into a single
/// handler that executes them in sequence.
pub trait EventHandleExt<T: Send + Sync>: EventHandle<T> {
    /// Combines this handler with another handler, creating a new handler that
    /// runs both in sequence
    ///
    /// When an event is handled, both handlers run in sequence.
    ///
    /// # Arguments
    /// * `other` - Another handler to combine with this one
    ///
    /// # Returns
    /// A new boxed handler that combines both handlers
    fn and<H: EventHandle<T> + 'static>(self, other: H) -> Box<dyn EventHandle<T>>
    where
        Self: Sized + 'static;
}

impl<T: Send + Sync + 'static, A: EventHandle<T> + 'static> EventHandleExt<T> for A {
    fn and<H: EventHandle<T> + 'static>(self, other: H) -> Box<dyn EventHandle<T>>
    where
        Self: Sized + 'static,
    {
        Box::new(CombinedHandler(Box::new(self), Box::new(other)))
    }
}

// Implement EventHandle for Box<dyn EventHandle> to allow using boxed handlers
#[async_trait]
impl<T: Send + Sync> EventHandle<T> for Box<dyn EventHandle<T>> {
    async fn handle(&self, event: &T, conversation: &mut Conversation) -> anyhow::Result<()> {
        (**self).handle(event, conversation).await
    }
}

/// A hook that contains handlers for all lifecycle events
///
/// Hooks allow you to attach custom behavior at specific points
/// during conversation processing.
pub struct Hook {
    on_start: Box<dyn EventHandle<EventData<StartPayload>>>,
    on_end: Box<dyn EventHandle<EventData<EndPayload>>>,
    on_request: Box<dyn EventHandle<EventData<RequestPayload>>>,
    on_response: Box<dyn EventHandle<EventData<ResponsePayload>>>,
    on_toolcall_start: Box<dyn EventHandle<EventData<ToolcallStartPayload>>>,
    on_toolcall_end: Box<dyn EventHandle<EventData<ToolcallEndPayload>>>,
}

impl Default for Hook {
    fn default() -> Self {
        Self {
            on_start: Box::new(NoOpHandler),
            on_end: Box::new(NoOpHandler),
            on_request: Box::new(NoOpHandler),
            on_response: Box::new(NoOpHandler),
            on_toolcall_start: Box::new(NoOpHandler),
            on_toolcall_end: Box::new(NoOpHandler),
        }
    }
}

impl Hook {
    /// Creates a new hook with custom handlers for all event types
    ///
    /// # Arguments
    /// * `on_start` - Handler for start events
    /// * `on_end` - Handler for end events
    /// * `on_request` - Handler for request events
    /// * `on_response` - Handler for response events
    /// * `on_toolcall_start` - Handler for tool call start events
    /// * `on_toolcall_end` - Handler for tool call end events
    pub fn new(
        on_start: impl Into<Box<dyn EventHandle<EventData<StartPayload>>>>,
        on_end: impl Into<Box<dyn EventHandle<EventData<EndPayload>>>>,
        on_request: impl Into<Box<dyn EventHandle<EventData<RequestPayload>>>>,
        on_response: impl Into<Box<dyn EventHandle<EventData<ResponsePayload>>>>,
        on_toolcall_start: impl Into<Box<dyn EventHandle<EventData<ToolcallStartPayload>>>>,
        on_toolcall_end: impl Into<Box<dyn EventHandle<EventData<ToolcallEndPayload>>>>,
    ) -> Self {
        Self {
            on_start: on_start.into(),
            on_end: on_end.into(),
            on_request: on_request.into(),
            on_response: on_response.into(),
            on_toolcall_start: on_toolcall_start.into(),
            on_toolcall_end: on_toolcall_end.into(),
        }
    }
}

impl Hook {
    /// Sets the start event handler
    ///
    /// # Arguments
    /// * `handler` - Handler for start events (automatically boxed)
    pub fn on_start(
        mut self,
        handler: impl EventHandle<EventData<StartPayload>> + 'static,
    ) -> Self {
        self.on_start = Box::new(handler);
        self
    }

    /// Sets the end event handler
    ///
    /// # Arguments
    /// * `handler` - Handler for end events (automatically boxed)
    pub fn on_end(mut self, handler: impl EventHandle<EventData<EndPayload>> + 'static) -> Self {
        self.on_end = Box::new(handler);
        self
    }

    /// Sets the request event handler
    ///
    /// # Arguments
    /// * `handler` - Handler for request events (automatically boxed)
    pub fn on_request(
        mut self,
        handler: impl EventHandle<EventData<RequestPayload>> + 'static,
    ) -> Self {
        self.on_request = Box::new(handler);
        self
    }

    /// Sets the response event handler
    ///
    /// # Arguments
    /// * `handler` - Handler for response events (automatically boxed)
    pub fn on_response(
        mut self,
        handler: impl EventHandle<EventData<ResponsePayload>> + 'static,
    ) -> Self {
        self.on_response = Box::new(handler);
        self
    }

    /// Sets the tool call start event handler
    ///
    /// # Arguments
    /// * `handler` - Handler for tool call start events (automatically boxed)
    pub fn on_toolcall_start(
        mut self,
        handler: impl EventHandle<EventData<ToolcallStartPayload>> + 'static,
    ) -> Self {
        self.on_toolcall_start = Box::new(handler);
        self
    }

    /// Sets the tool call end event handler
    ///
    /// # Arguments
    /// * `handler` - Handler for tool call end events (automatically boxed)
    pub fn on_toolcall_end(
        mut self,
        handler: impl EventHandle<EventData<ToolcallEndPayload>> + 'static,
    ) -> Self {
        self.on_toolcall_end = Box::new(handler);
        self
    }
}

impl Hook {
    /// Combines this hook with another hook, creating a new hook that runs both
    /// handlers in sequence
    ///
    /// When an event is handled, the first hook's handler runs first, then the
    /// second hook's handler runs.
    ///
    /// # Arguments
    /// * `other` - Another hook to combine with this one
    ///
    /// # Returns
    /// A new hook that combines both hooks' handlers
    pub fn zip(self, other: Hook) -> Self {
        Self {
            on_start: self.on_start.and(other.on_start),
            on_end: self.on_end.and(other.on_end),
            on_request: self.on_request.and(other.on_request),
            on_response: self.on_response.and(other.on_response),
            on_toolcall_start: self.on_toolcall_start.and(other.on_toolcall_start),
            on_toolcall_end: self.on_toolcall_end.and(other.on_toolcall_end),
        }
    }
}

// Implement EventHandle for Hook to allow hooks to handle LifecycleEvent
#[async_trait]
impl EventHandle<LifecycleEvent> for Hook {
    async fn handle(
        &self,
        event: &LifecycleEvent,
        conversation: &mut Conversation,
    ) -> anyhow::Result<()> {
        match &event {
            LifecycleEvent::Start(data) => self.on_start.handle(data, conversation).await,
            LifecycleEvent::End(data) => self.on_end.handle(data, conversation).await,
            LifecycleEvent::Request(data) => self.on_request.handle(data, conversation).await,
            LifecycleEvent::Response(data) => self.on_response.handle(data, conversation).await,
            LifecycleEvent::ToolcallStart(data) => {
                self.on_toolcall_start.handle(data, conversation).await
            }
            LifecycleEvent::ToolcallEnd(data) => {
                self.on_toolcall_end.handle(data, conversation).await
            }
        }
    }
}

/// A handler that combines two event handlers with sequential execution
///
/// Runs the first handler, then runs the second handler.
///
/// This is used internally by the `Hook::zip` and `EventHandleExt::and`
/// methods.
struct CombinedHandler<T: Send + Sync>(Box<dyn EventHandle<T>>, Box<dyn EventHandle<T>>);

#[async_trait]
impl<T: Send + Sync> EventHandle<T> for CombinedHandler<T> {
    async fn handle(&self, event: &T, conversation: &mut Conversation) -> anyhow::Result<()> {
        // Run the first handler
        self.0.handle(event, conversation).await?;
        // Run the second handler with the cloned event
        self.1.handle(event, conversation).await
    }
}

/// A no-op handler that does nothing
///
/// This is useful as a default handler when you only want to
/// handle specific events.
#[derive(Debug, Default)]
pub struct NoOpHandler;

#[async_trait]
impl<T: Send + Sync> EventHandle<T> for NoOpHandler {
    async fn handle(&self, _: &T, _: &mut Conversation) -> anyhow::Result<()> {
        Ok(())
    }
}

#[async_trait]
impl<T: Send + Sync, F, Fut> EventHandle<T> for F
where
    F: Fn(&T, &mut Conversation) -> Fut + Send + Sync,
    Fut: std::future::Future<Output = anyhow::Result<()>> + Send,
{
    async fn handle(&self, event: &T, conversation: &mut Conversation) -> anyhow::Result<()> {
        (self)(event, conversation).await
    }
}

impl<T: Send + Sync, F, Fut> From<F> for Box<dyn EventHandle<T>>
where
    F: Fn(&T, &mut Conversation) -> Fut + Send + Sync + 'static,
    Fut: std::future::Future<Output = anyhow::Result<()>> + Send + 'static,
{
    fn from(handler: F) -> Self {
        Box::new(handler)
    }
}

#[cfg(test)]
mod tests {
    use pretty_assertions::assert_eq;

    use super::*;
    use crate::{Agent, AgentId, Conversation, ModelId, ProviderId};

    fn test_agent() -> Agent {
        Agent::new(
            AgentId::new("test_agent"),
            ProviderId::FORGE,
            ModelId::new("test-model"),
        )
    }

    fn test_model_id() -> ModelId {
        ModelId::new("test-model")
    }

    #[test]
    fn test_no_op_handler() {
        let handler = NoOpHandler;
        let conversation = Conversation::generate();

        // This test just ensures NoOpHandler compiles and is constructible
        let _ = handler;
        let _ = conversation;
    }

    #[tokio::test]
    async fn test_hook_on_start() {
        let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let events_clone = events.clone();

        let hook = Hook::default().on_start(
            move |event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                let events = events_clone.clone();
                let event = event.clone();
                async move {
                    events.lock().unwrap().push(event);
                    Ok(())
                }
            },
        );

        let mut conversation = Conversation::generate();

        hook.handle(
            &LifecycleEvent::Start(EventData::new(test_agent(), test_model_id(), StartPayload)),
            &mut conversation,
        )
        .await
        .unwrap();

        let handled = events.lock().unwrap();
        assert_eq!(handled.len(), 1);
        assert_eq!(
            handled[0],
            EventData::new(test_agent(), test_model_id(), StartPayload)
        );
    }

    #[tokio::test]
    async fn test_hook_builder() {
        let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));

        let hook = Hook::default()
            .on_start({
                let events = events.clone();
                move |event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                    let events = events.clone();
                    let event = LifecycleEvent::Start(event.clone());
                    async move {
                        events.lock().unwrap().push(event);
                        Ok(())
                    }
                }
            })
            .on_end({
                let events = events.clone();
                move |event: &EventData<EndPayload>, _conversation: &mut Conversation| {
                    let events = events.clone();
                    let event = LifecycleEvent::End(event.clone());
                    async move {
                        events.lock().unwrap().push(event);
                        Ok(())
                    }
                }
            })
            .on_request({
                let events = events.clone();
                move |event: &EventData<RequestPayload>, _conversation: &mut Conversation| {
                    let events = events.clone();
                    let event = LifecycleEvent::Request(event.clone());
                    async move {
                        events.lock().unwrap().push(event);
                        Ok(())
                    }
                }
            });

        let mut conversation = Conversation::generate();

        // Test Start event
        hook.handle(
            &LifecycleEvent::Start(EventData::new(test_agent(), test_model_id(), StartPayload)),
            &mut conversation,
        )
        .await
        .unwrap();
        // Test End event
        hook.handle(
            &LifecycleEvent::End(EventData::new(test_agent(), test_model_id(), EndPayload)),
            &mut conversation,
        )
        .await
        .unwrap();
        // Test Request event
        hook.handle(
            &LifecycleEvent::Request(EventData::new(
                test_agent(),
                test_model_id(),
                RequestPayload::new(1),
            )),
            &mut conversation,
        )
        .await
        .unwrap();

        let handled = events.lock().unwrap();
        assert_eq!(handled.len(), 3);
        assert_eq!(
            handled[0],
            LifecycleEvent::Start(EventData::new(test_agent(), test_model_id(), StartPayload))
        );
        assert_eq!(
            handled[1],
            LifecycleEvent::End(EventData::new(test_agent(), test_model_id(), EndPayload))
        );
        assert_eq!(
            handled[2],
            LifecycleEvent::Request(EventData::new(
                test_agent(),
                test_model_id(),
                RequestPayload::new(1)
            ))
        );
    }

    #[tokio::test]
    async fn test_hook_all_events() {
        let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));

        let hook = Hook::new(
            {
                let events = events.clone();
                move |event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                    let events = events.clone();
                    let event = LifecycleEvent::Start(event.clone());
                    async move {
                        events.lock().unwrap().push(event);
                        Ok(())
                    }
                }
            },
            {
                let events = events.clone();
                move |event: &EventData<EndPayload>, _conversation: &mut Conversation| {
                    let events = events.clone();
                    let event = LifecycleEvent::End(event.clone());
                    async move {
                        events.lock().unwrap().push(event);
                        Ok(())
                    }
                }
            },
            {
                let events = events.clone();
                move |event: &EventData<RequestPayload>, _conversation: &mut Conversation| {
                    let events = events.clone();
                    let event = LifecycleEvent::Request(event.clone());
                    async move {
                        events.lock().unwrap().push(event);
                        Ok(())
                    }
                }
            },
            {
                let events = events.clone();
                move |event: &EventData<ResponsePayload>, _conversation: &mut Conversation| {
                    let events = events.clone();
                    let event = LifecycleEvent::Response(event.clone());
                    async move {
                        events.lock().unwrap().push(event);
                        Ok(())
                    }
                }
            },
            {
                let events = events.clone();
                move |event: &EventData<ToolcallStartPayload>, _conversation: &mut Conversation| {
                    let events = events.clone();
                    let event = LifecycleEvent::ToolcallStart(event.clone());
                    async move {
                        events.lock().unwrap().push(event);
                        Ok(())
                    }
                }
            },
            {
                let events = events.clone();
                move |event: &EventData<ToolcallEndPayload>, _conversation: &mut Conversation| {
                    let events = events.clone();
                    let event = LifecycleEvent::ToolcallEnd(event.clone());
                    async move {
                        events.lock().unwrap().push(event);
                        Ok(())
                    }
                }
            },
        );

        let mut conversation = Conversation::generate();

        let all_events = vec![
            LifecycleEvent::Start(EventData::new(test_agent(), test_model_id(), StartPayload)),
            LifecycleEvent::End(EventData::new(test_agent(), test_model_id(), EndPayload)),
            LifecycleEvent::Request(EventData::new(
                test_agent(),
                test_model_id(),
                RequestPayload::new(1),
            )),
            LifecycleEvent::Response(EventData::new(
                test_agent(),
                test_model_id(),
                ResponsePayload::new(ChatCompletionMessageFull {
                    content: "test".to_string(),
                    reasoning: None,
                    tool_calls: vec![],
                    thought_signature: None,
                    reasoning_details: None,
                    usage: crate::Usage::default(),
                    finish_reason: None,
                    phase: None,
                }),
            )),
            LifecycleEvent::ToolcallStart(EventData::new(
                test_agent(),
                test_model_id(),
                ToolcallStartPayload::new(ToolCallFull::new("test_tool")),
            )),
            LifecycleEvent::ToolcallEnd(EventData::new(
                test_agent(),
                test_model_id(),
                ToolcallEndPayload::new(
                    ToolCallFull::new("test_tool"),
                    ToolResult::new("test_tool"),
                ),
            )),
        ];

        for event in all_events {
            hook.handle(&event, &mut conversation).await.unwrap();
        }

        let handled = events.lock().unwrap();
        assert_eq!(handled.len(), 6);
    }

    #[tokio::test]
    async fn test_step_mutable_conversation() {
        let title = std::sync::Arc::new(std::sync::Mutex::new(None));
        let hook = Hook::default().on_start({
            let title = title.clone();
            move |_event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                let title = title.clone();
                async move {
                    *title.lock().unwrap() = Some("Modified title".to_string());
                    Ok(())
                }
            }
        });
        let mut conversation = Conversation::generate();

        assert!(title.lock().unwrap().is_none());

        hook.handle(
            &LifecycleEvent::Start(EventData::new(test_agent(), test_model_id(), StartPayload)),
            &mut conversation,
        )
        .await
        .unwrap();

        assert_eq!(*title.lock().unwrap(), Some("Modified title".to_string()));
    }

    #[test]
    fn test_hook_default() {
        let hook = Hook::default();

        // Just ensure it compiles and is constructible
        let _ = hook;
    }

    #[tokio::test]
    async fn test_hook_zip() {
        let counter1 = std::sync::Arc::new(std::sync::Mutex::new(0));
        let counter2 = std::sync::Arc::new(std::sync::Mutex::new(0));

        let hook1 = Hook::default().on_start({
            let counter = counter1.clone();
            move |_event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                let counter = counter.clone();
                async move {
                    *counter.lock().unwrap() += 1;
                    Ok(())
                }
            }
        });

        let hook2 = Hook::default().on_start({
            let counter = counter2.clone();
            move |_event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                let counter = counter.clone();
                async move {
                    *counter.lock().unwrap() += 1;
                    Ok(())
                }
            }
        });
        let combined: Hook = hook1.zip(hook2);

        let mut conversation = Conversation::generate();
        combined
            .handle(
                &LifecycleEvent::Start(EventData::new(test_agent(), test_model_id(), StartPayload)),
                &mut conversation,
            )
            .await
            .unwrap();

        // Both handlers should have been called
        assert_eq!(*counter1.lock().unwrap(), 1);
        assert_eq!(*counter2.lock().unwrap(), 1);
    }

    #[tokio::test]
    async fn test_hook_zip_multiple() {
        let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));

        let hook1 = Hook::default().on_start({
            let events = events.clone();
            move |event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                let events = events.clone();
                let event = event.clone();
                async move {
                    events.lock().unwrap().push(format!("h1:{:?}", event));
                    Ok(())
                }
            }
        });

        let hook2 = Hook::default().on_start({
            let events = events.clone();
            move |event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                let events = events.clone();
                let event = event.clone();
                async move {
                    events.lock().unwrap().push(format!("h2:{:?}", event));
                    Ok(())
                }
            }
        });

        let hook3 = Hook::default().on_start({
            let events = events.clone();
            move |event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                let events = events.clone();
                let event = event.clone();
                async move {
                    events.lock().unwrap().push(format!("h3:{:?}", event));
                    Ok(())
                }
            }
        });
        let combined: Hook = hook1.zip(hook2).zip(hook3);

        let mut conversation = Conversation::generate();
        combined
            .handle(
                &LifecycleEvent::Start(EventData::new(test_agent(), test_model_id(), StartPayload)),
                &mut conversation,
            )
            .await
            .unwrap();

        let handled = events.lock().unwrap();
        assert_eq!(handled.len(), 3);
        assert!(handled[0].starts_with("h1:EventData"));
        assert!(handled[1].starts_with("h2:EventData"));
        assert!(handled[2].starts_with("h3:EventData"));
    }

    #[tokio::test]
    async fn test_hook_zip_different_events() {
        let start_title = std::sync::Arc::new(std::sync::Mutex::new(None));
        let end_title = std::sync::Arc::new(std::sync::Mutex::new(None));

        let hook1 = Hook::default()
            .on_start({
                let start_title = start_title.clone();
                move |_event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                    let start_title = start_title.clone();
                    async move {
                        *start_title.lock().unwrap() = Some("Start".to_string());
                        Ok(())
                    }
                }
            })
            .on_end({
                let end_title = end_title.clone();
                move |_event: &EventData<EndPayload>, _conversation: &mut Conversation| {
                    let end_title = end_title.clone();
                    async move {
                        *end_title.lock().unwrap() = Some("End".to_string());
                        Ok(())
                    }
                }
            });
        let hook2 = Hook::default();

        let combined: Hook = hook1.zip(hook2);

        let mut conversation = Conversation::generate();

        // Test Start event
        combined
            .handle(
                &LifecycleEvent::Start(EventData::new(test_agent(), test_model_id(), StartPayload)),
                &mut conversation,
            )
            .await
            .unwrap();
        assert_eq!(*start_title.lock().unwrap(), Some("Start".to_string()));

        // Test End event
        combined
            .handle(
                &LifecycleEvent::End(EventData::new(test_agent(), test_model_id(), EndPayload)),
                &mut conversation,
            )
            .await
            .unwrap();
        assert_eq!(*end_title.lock().unwrap(), Some("End".to_string()));
    }

    #[tokio::test]
    async fn test_event_handle_ext_and() {
        let counter1 = std::sync::Arc::new(std::sync::Mutex::new(0));
        let counter2 = std::sync::Arc::new(std::sync::Mutex::new(0));

        let handler1 = {
            let counter = counter1.clone();
            move |_event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                let counter = counter.clone();
                async move {
                    *counter.lock().unwrap() += 1;
                    Ok(())
                }
            }
        };

        let handler2 = {
            let counter = counter2.clone();
            move |_event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                let counter = counter.clone();
                async move {
                    *counter.lock().unwrap() += 1;
                    Ok(())
                }
            }
        };

        let combined: Box<dyn EventHandle<EventData<StartPayload>>> = handler1.and(handler2);

        let mut conversation = Conversation::generate();
        combined
            .handle(
                &EventData::new(test_agent(), test_model_id(), StartPayload),
                &mut conversation,
            )
            .await
            .unwrap();

        // Both handlers should have been called
        assert_eq!(*counter1.lock().unwrap(), 1);
        assert_eq!(*counter2.lock().unwrap(), 1);
    }

    #[tokio::test]
    async fn test_event_handle_ext_and_boxed() {
        let counter1 = std::sync::Arc::new(std::sync::Mutex::new(0));
        let counter2 = std::sync::Arc::new(std::sync::Mutex::new(0));

        let handler1 = {
            let counter = counter1.clone();
            move |_event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                let counter = counter.clone();
                async move {
                    *counter.lock().unwrap() += 1;
                    Ok(())
                }
            }
        };

        let handler2 = {
            let counter = counter2.clone();
            move |_event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                let counter = counter.clone();
                async move {
                    *counter.lock().unwrap() += 1;
                    Ok(())
                }
            }
        };

        let combined: Box<dyn EventHandle<EventData<StartPayload>>> = handler1.and(handler2);

        let mut conversation = Conversation::generate();
        combined
            .handle(
                &EventData::new(test_agent(), test_model_id(), StartPayload),
                &mut conversation,
            )
            .await
            .unwrap();

        // Both handlers should have been called
        assert_eq!(*counter1.lock().unwrap(), 1);
        assert_eq!(*counter2.lock().unwrap(), 1);
    }

    #[tokio::test]
    async fn test_event_handle_ext_chain() {
        let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));

        let handler1 = {
            let events = events.clone();
            move |event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                let events = events.clone();
                let event = event.clone();
                async move {
                    events.lock().unwrap().push(format!("h1:{:?}", event));
                    Ok(())
                }
            }
        };

        let handler2 = {
            let events = events.clone();
            move |event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                let events = events.clone();
                let event = event.clone();
                async move {
                    events.lock().unwrap().push(format!("h2:{:?}", event));
                    Ok(())
                }
            }
        };

        let handler3 = {
            let events = events.clone();
            move |event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                let events = events.clone();
                let event = event.clone();
                async move {
                    events.lock().unwrap().push(format!("h3:{:?}", event));
                    Ok(())
                }
            }
        };

        // Chain handlers using and()
        let combined: Box<dyn EventHandle<EventData<StartPayload>>> =
            handler1.and(handler2).and(handler3);

        let mut conversation = Conversation::generate();
        combined
            .handle(
                &EventData::new(test_agent(), test_model_id(), StartPayload),
                &mut conversation,
            )
            .await
            .unwrap();

        let handled = events.lock().unwrap();
        assert_eq!(handled.len(), 3);
        assert!(handled[0].starts_with("h1:EventData"));
        assert!(handled[1].starts_with("h2:EventData"));
        assert!(handled[2].starts_with("h3:EventData"));
    }

    #[tokio::test]
    async fn test_event_handle_ext_with_hook() {
        let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let start_title = std::sync::Arc::new(std::sync::Mutex::new(None));

        let start_handler = {
            let start_title = start_title.clone();
            move |_event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                let start_title = start_title.clone();
                async move {
                    *start_title.lock().unwrap() = Some("Started".to_string());
                    Ok(())
                }
            }
        };

        let logging_handler = {
            let events = events.clone();
            move |event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                let events = events.clone();
                let event = event.clone();
                async move {
                    events.lock().unwrap().push(format!("Event: {:?}", event));
                    Ok(())
                }
            }
        };

        // Combine handlers using extension trait
        let combined_handler: Box<dyn EventHandle<EventData<StartPayload>>> =
            start_handler.and(logging_handler);

        let hook = Hook::default().on_start(combined_handler);

        let mut conversation = Conversation::generate();
        hook.handle(
            &LifecycleEvent::Start(EventData::new(test_agent(), test_model_id(), StartPayload)),
            &mut conversation,
        )
        .await
        .unwrap();

        assert_eq!(events.lock().unwrap().len(), 1);
        assert!(events.lock().unwrap()[0].starts_with("Event: EventData"));
    }

    #[tokio::test]
    async fn test_hook_as_event_handle() {
        let start_title = std::sync::Arc::new(std::sync::Mutex::new(None));
        let end_title = std::sync::Arc::new(std::sync::Mutex::new(None));

        let hook = Hook::default()
            .on_start({
                let start_title = start_title.clone();
                move |_event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                    let start_title = start_title.clone();
                    async move {
                        *start_title.lock().unwrap() = Some("Started".to_string());
                        Ok(())
                    }
                }
            })
            .on_end({
                let end_title = end_title.clone();
                move |_event: &EventData<EndPayload>, _conversation: &mut Conversation| {
                    let end_title = end_title.clone();
                    async move {
                        *end_title.lock().unwrap() = Some("Ended".to_string());
                        Ok(())
                    }
                }
            });

        // Test using handle() directly (EventHandle trait)
        let mut conversation = Conversation::generate();
        hook.handle(
            &LifecycleEvent::Start(EventData::new(test_agent(), test_model_id(), StartPayload)),
            &mut conversation,
        )
        .await
        .unwrap();
        assert_eq!(*start_title.lock().unwrap(), Some("Started".to_string()));

        hook.handle(
            &LifecycleEvent::End(EventData::new(test_agent(), test_model_id(), EndPayload)),
            &mut conversation,
        )
        .await
        .unwrap();
        assert_eq!(*end_title.lock().unwrap(), Some("Ended".to_string()));
    }

    #[tokio::test]
    async fn test_hook_combination_with_and() {
        let hook1_title = std::sync::Arc::new(std::sync::Mutex::new(None));
        let hook2_title = std::sync::Arc::new(std::sync::Mutex::new(None));

        let handler1 = {
            let hook1_title = hook1_title.clone();
            move |_event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                let hook1_title = hook1_title.clone();
                async move {
                    *hook1_title.lock().unwrap() = Some("Started".to_string());
                    Ok(())
                }
            }
        };
        let handler2 = {
            let hook2_title = hook2_title.clone();
            move |_event: &EventData<StartPayload>, _conversation: &mut Conversation| {
                let hook2_title = hook2_title.clone();
                async move {
                    *hook2_title.lock().unwrap() = Some("Ended".to_string());
                    Ok(())
                }
            }
        };

        // Combine handlers using and() extension method
        let combined: Box<dyn EventHandle<EventData<StartPayload>>> = handler1.and(handler2);

        let mut conversation = Conversation::generate();
        combined
            .handle(
                &EventData::new(test_agent(), test_model_id(), StartPayload),
                &mut conversation,
            )
            .await
            .unwrap();

        // Both handlers should have been called
        assert_eq!(*hook1_title.lock().unwrap(), Some("Started".to_string()));
        assert_eq!(*hook2_title.lock().unwrap(), Some("Ended".to_string()));
    }
}