cc-agent-sdk 0.1.7

claude agent sdk
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
//! Hook types for Claude Agent SDK

use futures::future::BoxFuture;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use typed_builder::TypedBuilder;

/// Hook events that can be intercepted
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum HookEvent {
    /// Before tool use
    PreToolUse,
    /// After tool use
    PostToolUse,
    /// When user prompt is submitted
    UserPromptSubmit,
    /// When execution stops
    Stop,
    /// When subagent stops
    SubagentStop,
    /// Before compacting conversation
    PreCompact,
}

/// Hook matcher for pattern-based hook registration
#[derive(Clone, TypedBuilder)]
#[builder(doc)]
pub struct HookMatcher {
    /// Optional matcher pattern (e.g., tool name)
    #[builder(default, setter(into, strip_option))]
    pub matcher: Option<String>,
    /// Hook callbacks to invoke
    #[builder(default)]
    pub hooks: Vec<HookCallback>,
    /// Timeout in seconds for all hooks in this matcher (default: 60)
    #[builder(default, setter(strip_option))]
    pub timeout: Option<f64>,
}

/// Hook callback type
pub type HookCallback = Arc<
    dyn Fn(HookInput, Option<String>, HookContext) -> BoxFuture<'static, HookJsonOutput>
        + Send
        + Sync,
>;

/// Hook function type that users implement
pub type HookFn = fn(HookInput, Option<String>, HookContext) -> BoxFuture<'static, HookJsonOutput>;

/// Input to hook callbacks
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "hook_event_name", rename_all = "PascalCase")]
pub enum HookInput {
    /// Pre-tool-use hook input
    PreToolUse(PreToolUseHookInput),
    /// Post-tool-use hook input
    PostToolUse(PostToolUseHookInput),
    /// User-prompt-submit hook input
    UserPromptSubmit(UserPromptSubmitHookInput),
    /// Stop hook input
    Stop(StopHookInput),
    /// Subagent-stop hook input
    SubagentStop(SubagentStopHookInput),
    /// Pre-compact hook input
    PreCompact(PreCompactHookInput),
}

/// Pre-tool-use hook input
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PreToolUseHookInput {
    /// Session ID
    pub session_id: String,
    /// Transcript path
    pub transcript_path: String,
    /// Current working directory
    pub cwd: String,
    /// Permission mode
    #[serde(skip_serializing_if = "Option::is_none")]
    pub permission_mode: Option<String>,
    /// Tool name being used
    pub tool_name: String,
    /// Tool input parameters
    pub tool_input: serde_json::Value,
}

/// Post-tool-use hook input
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PostToolUseHookInput {
    /// Session ID
    pub session_id: String,
    /// Transcript path
    pub transcript_path: String,
    /// Current working directory
    pub cwd: String,
    /// Permission mode
    #[serde(skip_serializing_if = "Option::is_none")]
    pub permission_mode: Option<String>,
    /// Tool name that was used
    pub tool_name: String,
    /// Tool input parameters
    pub tool_input: serde_json::Value,
    /// Tool response (output from the tool)
    pub tool_response: serde_json::Value,
}

/// User-prompt-submit hook input
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserPromptSubmitHookInput {
    /// Session ID
    pub session_id: String,
    /// Transcript path
    pub transcript_path: String,
    /// Current working directory
    pub cwd: String,
    /// Permission mode
    #[serde(skip_serializing_if = "Option::is_none")]
    pub permission_mode: Option<String>,
    /// User prompt
    pub prompt: String,
}

/// Stop hook input
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StopHookInput {
    /// Session ID
    pub session_id: String,
    /// Transcript path
    pub transcript_path: String,
    /// Current working directory
    pub cwd: String,
    /// Permission mode
    #[serde(skip_serializing_if = "Option::is_none")]
    pub permission_mode: Option<String>,
    /// Whether stop hook is active
    pub stop_hook_active: bool,
}

/// Subagent-stop hook input
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubagentStopHookInput {
    /// Session ID
    pub session_id: String,
    /// Transcript path
    pub transcript_path: String,
    /// Current working directory
    pub cwd: String,
    /// Permission mode
    #[serde(skip_serializing_if = "Option::is_none")]
    pub permission_mode: Option<String>,
    /// Whether stop hook is active
    pub stop_hook_active: bool,
}

/// Pre-compact hook input
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PreCompactHookInput {
    /// Session ID
    pub session_id: String,
    /// Transcript path
    pub transcript_path: String,
    /// Current working directory
    pub cwd: String,
    /// Permission mode
    #[serde(skip_serializing_if = "Option::is_none")]
    pub permission_mode: Option<String>,
    /// Trigger type (manual or auto)
    pub trigger: String,
    /// Custom instructions for compaction
    #[serde(skip_serializing_if = "Option::is_none")]
    pub custom_instructions: Option<String>,
}

/// Hook context passed to callbacks
#[derive(Debug, Clone, Default)]
pub struct HookContext {
    /// Abort signal (future feature)
    pub signal: Option<()>,
}

/// Hook output (can be async or sync)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum HookJsonOutput {
    /// Async hook output (returns immediately, hook continues in background)
    Async(AsyncHookJsonOutput),
    /// Sync hook output (blocks until hook completes)
    Sync(SyncHookJsonOutput),
}

/// Async hook output
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AsyncHookJsonOutput {
    /// Async field (always true to indicate async mode)
    /// Note: In Rust this field is named `async_` to avoid keyword conflict,
    /// but it serializes to "async" for the CLI
    #[serde(rename = "async")]
    pub async_: bool,
    /// Async timeout in milliseconds
    #[serde(skip_serializing_if = "Option::is_none", rename = "asyncTimeout")]
    pub async_timeout: Option<u64>,
}

impl Default for AsyncHookJsonOutput {
    fn default() -> Self {
        Self {
            async_: true, // Always true for async hooks
            async_timeout: None,
        }
    }
}

/// Sync hook output
#[derive(Debug, Clone, Serialize, Deserialize, TypedBuilder)]
#[builder(doc)]
pub struct SyncHookJsonOutput {
    /// Whether to continue execution
    #[serde(skip_serializing_if = "Option::is_none", rename = "continue")]
    #[builder(default, setter(strip_option))]
    pub continue_: Option<bool>,
    /// Whether to suppress output
    #[serde(skip_serializing_if = "Option::is_none", rename = "suppressOutput")]
    #[builder(default, setter(strip_option))]
    pub suppress_output: Option<bool>,
    /// Stop reason (if stopping)
    #[serde(skip_serializing_if = "Option::is_none", rename = "stopReason")]
    #[builder(default, setter(into, strip_option))]
    pub stop_reason: Option<String>,
    /// Permission decision
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(into, strip_option))]
    pub decision: Option<String>,
    /// System message to add
    #[serde(skip_serializing_if = "Option::is_none", rename = "systemMessage")]
    #[builder(default, setter(into, strip_option))]
    pub system_message: Option<String>,
    /// Reason for decision
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(into, strip_option))]
    pub reason: Option<String>,
    /// Hook-specific output
    #[serde(skip_serializing_if = "Option::is_none", rename = "hookSpecificOutput")]
    #[builder(default, setter(strip_option))]
    pub hook_specific_output: Option<HookSpecificOutput>,
}

impl Default for SyncHookJsonOutput {
    fn default() -> Self {
        Self::builder().build()
    }
}

/// Hook-specific output for different hook types
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "hookEventName")]
pub enum HookSpecificOutput {
    /// Pre-tool-use specific output
    PreToolUse(PreToolUseHookSpecificOutput),
    /// Post-tool-use specific output
    PostToolUse(PostToolUseHookSpecificOutput),
    /// User-prompt-submit specific output
    UserPromptSubmit(UserPromptSubmitHookSpecificOutput),
}

/// Pre-tool-use hook specific output
#[derive(Debug, Clone, Serialize, Deserialize, TypedBuilder)]
#[builder(doc)]
pub struct PreToolUseHookSpecificOutput {
    /// Permission decision (allow/deny/ask)
    #[serde(skip_serializing_if = "Option::is_none", rename = "permissionDecision")]
    #[builder(default, setter(into, strip_option))]
    pub permission_decision: Option<String>,
    /// Reason for permission decision
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "permissionDecisionReason"
    )]
    #[builder(default, setter(into, strip_option))]
    pub permission_decision_reason: Option<String>,
    /// Updated tool input
    #[serde(skip_serializing_if = "Option::is_none", rename = "updatedInput")]
    #[builder(default, setter(strip_option))]
    pub updated_input: Option<serde_json::Value>,
}

impl Default for PreToolUseHookSpecificOutput {
    fn default() -> Self {
        Self::builder().build()
    }
}

/// Post-tool-use hook specific output
#[derive(Debug, Clone, Serialize, Deserialize, TypedBuilder)]
#[builder(doc)]
pub struct PostToolUseHookSpecificOutput {
    /// Additional context to provide to Claude
    #[serde(skip_serializing_if = "Option::is_none", rename = "additionalContext")]
    #[builder(default, setter(into, strip_option))]
    pub additional_context: Option<String>,
}

impl Default for PostToolUseHookSpecificOutput {
    fn default() -> Self {
        Self::builder().build()
    }
}

/// User-prompt-submit hook specific output
#[derive(Debug, Clone, Serialize, Deserialize, TypedBuilder)]
#[builder(doc)]
pub struct UserPromptSubmitHookSpecificOutput {
    /// Additional context to provide to Claude
    #[serde(skip_serializing_if = "Option::is_none", rename = "additionalContext")]
    #[builder(default, setter(into, strip_option))]
    pub additional_context: Option<String>,
}

impl Default for UserPromptSubmitHookSpecificOutput {
    fn default() -> Self {
        Self::builder().build()
    }
}

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

    #[test]
    fn test_hook_event_serialization() {
        // HookEvent serializes to PascalCase to match Python SDK
        assert_eq!(
            serde_json::to_string(&HookEvent::PreToolUse).unwrap(),
            "\"PreToolUse\""
        );
        assert_eq!(
            serde_json::to_string(&HookEvent::PostToolUse).unwrap(),
            "\"PostToolUse\""
        );
        assert_eq!(
            serde_json::to_string(&HookEvent::UserPromptSubmit).unwrap(),
            "\"UserPromptSubmit\""
        );
        assert_eq!(serde_json::to_string(&HookEvent::Stop).unwrap(), "\"Stop\"");
        assert_eq!(
            serde_json::to_string(&HookEvent::SubagentStop).unwrap(),
            "\"SubagentStop\""
        );
        assert_eq!(
            serde_json::to_string(&HookEvent::PreCompact).unwrap(),
            "\"PreCompact\""
        );
    }

    #[test]
    fn test_pretooluse_hook_input_deserialization() {
        let json_str = r#"{
            "hook_event_name": "PreToolUse",
            "session_id": "test-session",
            "transcript_path": "/path/to/transcript",
            "cwd": "/working/dir",
            "permission_mode": "default",
            "tool_name": "Bash",
            "tool_input": {"command": "echo hello"}
        }"#;

        let input: HookInput = serde_json::from_str(json_str).unwrap();
        match input {
            HookInput::PreToolUse(pre_tool) => {
                assert_eq!(pre_tool.session_id, "test-session");
                assert_eq!(pre_tool.tool_name, "Bash");
                assert_eq!(pre_tool.tool_input["command"], "echo hello");
            },
            _ => panic!("Expected PreToolUse variant"),
        }
    }

    #[test]
    fn test_posttooluse_hook_input_deserialization() {
        let json_str = r#"{
            "hook_event_name": "PostToolUse",
            "session_id": "test-session",
            "transcript_path": "/path/to/transcript",
            "cwd": "/working/dir",
            "tool_name": "Bash",
            "tool_input": {"command": "echo hello"},
            "tool_response": "hello\n"
        }"#;

        let input: HookInput = serde_json::from_str(json_str).unwrap();
        match input {
            HookInput::PostToolUse(post_tool) => {
                assert_eq!(post_tool.session_id, "test-session");
                assert_eq!(post_tool.tool_name, "Bash");
                assert_eq!(post_tool.tool_response, "hello\n");
            },
            _ => panic!("Expected PostToolUse variant"),
        }
    }

    #[test]
    fn test_stop_hook_input_deserialization() {
        let json_str = r#"{
            "hook_event_name": "Stop",
            "session_id": "test-session",
            "transcript_path": "/path/to/transcript",
            "cwd": "/working/dir",
            "stop_hook_active": true
        }"#;

        let input: HookInput = serde_json::from_str(json_str).unwrap();
        match input {
            HookInput::Stop(stop) => {
                assert_eq!(stop.session_id, "test-session");
                assert!(stop.stop_hook_active);
            },
            _ => panic!("Expected Stop variant"),
        }
    }

    #[test]
    fn test_subagent_stop_hook_input_deserialization() {
        let json_str = r#"{
            "hook_event_name": "SubagentStop",
            "session_id": "test-session",
            "transcript_path": "/path/to/transcript",
            "cwd": "/working/dir",
            "stop_hook_active": false
        }"#;

        let input: HookInput = serde_json::from_str(json_str).unwrap();
        match input {
            HookInput::SubagentStop(subagent) => {
                assert_eq!(subagent.session_id, "test-session");
                assert!(!subagent.stop_hook_active);
            },
            _ => panic!("Expected SubagentStop variant"),
        }
    }

    #[test]
    fn test_precompact_hook_input_deserialization() {
        let json_str = r#"{
            "hook_event_name": "PreCompact",
            "session_id": "test-session",
            "transcript_path": "/path/to/transcript",
            "cwd": "/working/dir",
            "trigger": "manual",
            "custom_instructions": "Keep important details"
        }"#;

        let input: HookInput = serde_json::from_str(json_str).unwrap();
        match input {
            HookInput::PreCompact(precompact) => {
                assert_eq!(precompact.session_id, "test-session");
                assert_eq!(precompact.trigger, "manual");
                assert_eq!(
                    precompact.custom_instructions,
                    Some("Keep important details".to_string())
                );
            },
            _ => panic!("Expected PreCompact variant"),
        }
    }

    #[test]
    fn test_sync_hook_output_serialization() {
        let output = SyncHookJsonOutput {
            continue_: Some(false),
            stop_reason: Some("Test stop".to_string()),
            ..Default::default()
        };

        let json = serde_json::to_value(&output).unwrap();
        assert_eq!(json["continue"], false);
        assert_eq!(json["stopReason"], "Test stop");
    }

    #[test]
    fn test_hook_specific_output_pretooluse_serialization() {
        let output = HookSpecificOutput::PreToolUse(PreToolUseHookSpecificOutput {
            permission_decision: Some("deny".to_string()),
            permission_decision_reason: Some("Security policy".to_string()),
            updated_input: None,
        });

        let json = serde_json::to_value(&output).unwrap();
        assert_eq!(json["hookEventName"], "PreToolUse");
        assert_eq!(json["permissionDecision"], "deny");
        assert_eq!(json["permissionDecisionReason"], "Security policy");
    }

    #[test]
    fn test_hook_specific_output_posttooluse_serialization() {
        let output = HookSpecificOutput::PostToolUse(PostToolUseHookSpecificOutput {
            additional_context: Some("Error occurred".to_string()),
        });

        let json = serde_json::to_value(&output).unwrap();
        assert_eq!(json["hookEventName"], "PostToolUse");
        assert_eq!(json["additionalContext"], "Error occurred");
    }

    #[test]
    fn test_hook_specific_output_userpromptsubmit_serialization() {
        let output = HookSpecificOutput::UserPromptSubmit(UserPromptSubmitHookSpecificOutput {
            additional_context: Some("Custom context".to_string()),
        });

        let json = serde_json::to_value(&output).unwrap();
        assert_eq!(json["hookEventName"], "UserPromptSubmit");
        assert_eq!(json["additionalContext"], "Custom context");
    }

    #[test]
    fn test_complete_hook_output_with_pretooluse() {
        let output = SyncHookJsonOutput {
            continue_: Some(true),
            hook_specific_output: Some(HookSpecificOutput::PreToolUse(
                PreToolUseHookSpecificOutput {
                    permission_decision: Some("allow".to_string()),
                    permission_decision_reason: Some("Approved".to_string()),
                    updated_input: Some(json!({"modified": true})),
                },
            )),
            ..Default::default()
        };

        let json = serde_json::to_value(&output).unwrap();
        assert_eq!(json["continue"], true);
        assert_eq!(json["hookSpecificOutput"]["hookEventName"], "PreToolUse");
        assert_eq!(json["hookSpecificOutput"]["permissionDecision"], "allow");
    }

    #[test]
    fn test_optional_fields_omitted() {
        let output = SyncHookJsonOutput::default();
        let json = serde_json::to_value(&output).unwrap();

        // Default output should be an empty object
        assert!(json.as_object().unwrap().is_empty());
    }

    #[test]
    fn test_async_hook_output_serialization() {
        let output = AsyncHookJsonOutput::default();
        let json = serde_json::to_value(&output).unwrap();

        // Must have "async": true
        assert_eq!(json["async"], true);
        // asyncTimeout should not be present (None)
        assert!(json.get("asyncTimeout").is_none());
    }

    #[test]
    fn test_async_hook_output_with_timeout() {
        let output = AsyncHookJsonOutput {
            async_: true,
            async_timeout: Some(5000),
        };
        let json = serde_json::to_value(&output).unwrap();

        assert_eq!(json["async"], true);
        assert_eq!(json["asyncTimeout"], 5000);
    }

    #[test]
    fn test_hooks_builder_new() {
        let hooks = Hooks::new();
        let built = hooks.build();
        assert!(built.is_empty());
    }

    #[test]
    fn test_hooks_builder_add_pre_tool_use() {
        async fn test_hook(
            _input: HookInput,
            _tool_use_id: Option<String>,
            _context: HookContext,
        ) -> HookJsonOutput {
            HookJsonOutput::Sync(SyncHookJsonOutput::default())
        }

        let mut hooks = Hooks::new();
        hooks.add_pre_tool_use(test_hook);

        let built = hooks.build();
        assert_eq!(built.len(), 1);
        assert!(built.contains_key(&HookEvent::PreToolUse));

        let matchers = &built[&HookEvent::PreToolUse];
        assert_eq!(matchers.len(), 1);
        assert_eq!(matchers[0].matcher, None);
        assert_eq!(matchers[0].hooks.len(), 1);
    }

    #[test]
    fn test_hooks_builder_add_pre_tool_use_with_matcher() {
        async fn test_hook(
            _input: HookInput,
            _tool_use_id: Option<String>,
            _context: HookContext,
        ) -> HookJsonOutput {
            HookJsonOutput::Sync(SyncHookJsonOutput::default())
        }

        let mut hooks = Hooks::new();
        hooks.add_pre_tool_use_with_matcher("Bash", test_hook);

        let built = hooks.build();
        assert_eq!(built.len(), 1);
        assert!(built.contains_key(&HookEvent::PreToolUse));

        let matchers = &built[&HookEvent::PreToolUse];
        assert_eq!(matchers.len(), 1);
        assert_eq!(matchers[0].matcher, Some("Bash".to_string()));
        assert_eq!(matchers[0].hooks.len(), 1);
    }

    #[test]
    fn test_hooks_builder_multiple_hooks_same_event() {
        async fn test_hook1(
            _input: HookInput,
            _tool_use_id: Option<String>,
            _context: HookContext,
        ) -> HookJsonOutput {
            HookJsonOutput::Sync(SyncHookJsonOutput::default())
        }

        async fn test_hook2(
            _input: HookInput,
            _tool_use_id: Option<String>,
            _context: HookContext,
        ) -> HookJsonOutput {
            HookJsonOutput::Sync(SyncHookJsonOutput::default())
        }

        let mut hooks = Hooks::new();
        hooks.add_pre_tool_use(test_hook1);
        hooks.add_pre_tool_use_with_matcher("Bash", test_hook2);

        let built = hooks.build();
        assert_eq!(built.len(), 1);
        assert!(built.contains_key(&HookEvent::PreToolUse));

        let matchers = &built[&HookEvent::PreToolUse];
        assert_eq!(matchers.len(), 2);
        assert_eq!(matchers[0].matcher, None);
        assert_eq!(matchers[1].matcher, Some("Bash".to_string()));
    }

    #[test]
    fn test_hooks_builder_add_post_tool_use() {
        async fn test_hook(
            _input: HookInput,
            _tool_use_id: Option<String>,
            _context: HookContext,
        ) -> HookJsonOutput {
            HookJsonOutput::Sync(SyncHookJsonOutput::default())
        }

        let mut hooks = Hooks::new();
        hooks.add_post_tool_use(test_hook);

        let built = hooks.build();
        assert!(built.contains_key(&HookEvent::PostToolUse));
        assert_eq!(built[&HookEvent::PostToolUse][0].matcher, None);
    }

    #[test]
    fn test_hooks_builder_add_post_tool_use_with_matcher() {
        async fn test_hook(
            _input: HookInput,
            _tool_use_id: Option<String>,
            _context: HookContext,
        ) -> HookJsonOutput {
            HookJsonOutput::Sync(SyncHookJsonOutput::default())
        }

        let mut hooks = Hooks::new();
        hooks.add_post_tool_use_with_matcher("Write", test_hook);

        let built = hooks.build();
        assert!(built.contains_key(&HookEvent::PostToolUse));
        assert_eq!(
            built[&HookEvent::PostToolUse][0].matcher,
            Some("Write".to_string())
        );
    }

    #[test]
    fn test_hooks_builder_add_user_prompt_submit() {
        async fn test_hook(
            _input: HookInput,
            _tool_use_id: Option<String>,
            _context: HookContext,
        ) -> HookJsonOutput {
            HookJsonOutput::Sync(SyncHookJsonOutput::default())
        }

        let mut hooks = Hooks::new();
        hooks.add_user_prompt_submit(test_hook);

        let built = hooks.build();
        assert!(built.contains_key(&HookEvent::UserPromptSubmit));
        assert_eq!(built[&HookEvent::UserPromptSubmit][0].matcher, None);
    }

    #[test]
    fn test_hooks_builder_add_stop() {
        async fn test_hook(
            _input: HookInput,
            _tool_use_id: Option<String>,
            _context: HookContext,
        ) -> HookJsonOutput {
            HookJsonOutput::Sync(SyncHookJsonOutput::default())
        }

        let mut hooks = Hooks::new();
        hooks.add_stop(test_hook);

        let built = hooks.build();
        assert!(built.contains_key(&HookEvent::Stop));
        assert_eq!(built[&HookEvent::Stop][0].matcher, None);
    }

    #[test]
    fn test_hooks_builder_add_subagent_stop() {
        async fn test_hook(
            _input: HookInput,
            _tool_use_id: Option<String>,
            _context: HookContext,
        ) -> HookJsonOutput {
            HookJsonOutput::Sync(SyncHookJsonOutput::default())
        }

        let mut hooks = Hooks::new();
        hooks.add_subagent_stop(test_hook);

        let built = hooks.build();
        assert!(built.contains_key(&HookEvent::SubagentStop));
        assert_eq!(built[&HookEvent::SubagentStop][0].matcher, None);
    }

    #[test]
    fn test_hooks_builder_add_pre_compact() {
        async fn test_hook(
            _input: HookInput,
            _tool_use_id: Option<String>,
            _context: HookContext,
        ) -> HookJsonOutput {
            HookJsonOutput::Sync(SyncHookJsonOutput::default())
        }

        let mut hooks = Hooks::new();
        hooks.add_pre_compact(test_hook);

        let built = hooks.build();
        assert!(built.contains_key(&HookEvent::PreCompact));
        assert_eq!(built[&HookEvent::PreCompact][0].matcher, None);
    }

    #[test]
    fn test_hooks_builder_multiple_event_types() {
        async fn test_hook(
            _input: HookInput,
            _tool_use_id: Option<String>,
            _context: HookContext,
        ) -> HookJsonOutput {
            HookJsonOutput::Sync(SyncHookJsonOutput::default())
        }

        let mut hooks = Hooks::new();
        hooks.add_pre_tool_use(test_hook);
        hooks.add_post_tool_use(test_hook);
        hooks.add_user_prompt_submit(test_hook);
        hooks.add_stop(test_hook);

        let built = hooks.build();
        assert_eq!(built.len(), 4);
        assert!(built.contains_key(&HookEvent::PreToolUse));
        assert!(built.contains_key(&HookEvent::PostToolUse));
        assert!(built.contains_key(&HookEvent::UserPromptSubmit));
        assert!(built.contains_key(&HookEvent::Stop));
    }

    #[tokio::test]
    async fn test_hook_execution_returns_sync_output() {
        async fn test_hook(
            _input: HookInput,
            _tool_use_id: Option<String>,
            _context: HookContext,
        ) -> HookJsonOutput {
            HookJsonOutput::Sync(SyncHookJsonOutput {
                continue_: Some(true),
                ..Default::default()
            })
        }

        let mut hooks = Hooks::new();
        hooks.add_pre_tool_use(test_hook);

        let built = hooks.build();
        let hook_callback = &built[&HookEvent::PreToolUse][0].hooks[0];

        let input = HookInput::PreToolUse(PreToolUseHookInput {
            session_id: "test".to_string(),
            transcript_path: "/tmp/test".to_string(),
            cwd: "/tmp".to_string(),
            permission_mode: None,
            tool_name: "Bash".to_string(),
            tool_input: serde_json::json!({"command": "ls"}),
        });

        let result = hook_callback(input, None, HookContext::default()).await;
        match result {
            HookJsonOutput::Sync(output) => {
                assert_eq!(output.continue_, Some(true));
            },
            _ => panic!("Expected sync output"),
        }
    }

    #[tokio::test]
    async fn test_hook_execution_returns_async_output() {
        async fn test_hook(
            _input: HookInput,
            _tool_use_id: Option<String>,
            _context: HookContext,
        ) -> HookJsonOutput {
            HookJsonOutput::Async(AsyncHookJsonOutput {
                async_: true,
                async_timeout: Some(5000),
            })
        }

        let mut hooks = Hooks::new();
        hooks.add_pre_tool_use(test_hook);

        let built = hooks.build();
        let hook_callback = &built[&HookEvent::PreToolUse][0].hooks[0];

        let input = HookInput::PreToolUse(PreToolUseHookInput {
            session_id: "test".to_string(),
            transcript_path: "/tmp/test".to_string(),
            cwd: "/tmp".to_string(),
            permission_mode: None,
            tool_name: "Bash".to_string(),
            tool_input: serde_json::json!({"command": "ls"}),
        });

        let result = hook_callback(input, None, HookContext::default()).await;
        match result {
            HookJsonOutput::Async(output) => {
                assert!(output.async_);
                assert_eq!(output.async_timeout, Some(5000));
            },
            _ => panic!("Expected async output"),
        }
    }

    #[test]
    fn test_hooks_builder_matcher_accepts_string_types() {
        async fn test_hook(
            _input: HookInput,
            _tool_use_id: Option<String>,
            _context: HookContext,
        ) -> HookJsonOutput {
            HookJsonOutput::Sync(SyncHookJsonOutput::default())
        }

        let mut hooks = Hooks::new();

        // Test with &str
        hooks.add_pre_tool_use_with_matcher("Bash", test_hook);

        // Test with String
        hooks.add_pre_tool_use_with_matcher("Write".to_string(), test_hook);

        let built = hooks.build();
        let matchers = &built[&HookEvent::PreToolUse];
        assert_eq!(matchers.len(), 2);
        assert_eq!(matchers[0].matcher, Some("Bash".to_string()));
        assert_eq!(matchers[1].matcher, Some("Write".to_string()));
    }
}

/// Macro to generate hook methods for the Hooks builder
///
/// This macro generates two methods for each hook event:
/// 1. `add_<event>(&mut self, hook_fn)` - For hooks without matcher
/// 2. `add_<event>_with_matcher(&mut self, matcher, hook_fn)` - For hooks with matcher
macro_rules! generate_hook_methods {
    // Entry point - separate with_matcher and without
    (
        with_matcher: {
            $($event_m:ident => $method_name_m:ident: $doc_m:expr),* $(,)?
        },
        without_matcher: {
            $($event:ident => $method_name:ident: $doc:expr),* $(,)?
        } $(,)?
    ) => {
        $(
            generate_hook_methods!(@with_matcher $event_m, $method_name_m, $doc_m);
        )*
        $(
            generate_hook_methods!(@no_matcher $event, $method_name, $doc);
        )*
    };

    // Generate method with matcher support
    (@with_matcher $event:ident, $method_name:ident, $doc:expr) => {
        #[doc = $doc]
        pub fn $method_name<F, Fut>(&mut self, hook_fn: F)
        where
            F: Fn(HookInput, Option<String>, HookContext) -> Fut + Send + Sync + 'static,
            Fut: std::future::Future<Output = HookJsonOutput> + Send + 'static,
        {
            let wrapper = move |input: HookInput, tool_use_id: Option<String>, context: HookContext| {
                Box::pin(hook_fn(input, tool_use_id, context)) as BoxFuture<'static, HookJsonOutput>
            };
            self.add_hook(HookEvent::$event, None::<String>, wrapper);
        }

        paste::paste! {
            #[doc = $doc]
            #[doc = " with a matcher pattern."]
            #[doc = ""]
            #[doc = "# Arguments"]
            #[doc = "* `matcher` - Tool name to match (e.g., \"Bash\", \"Write\")"]
            #[doc = "* `hook_fn` - The hook function to call"]
            pub fn [<$method_name _with_matcher>]<F, Fut>(&mut self, matcher: impl Into<String>, hook_fn: F)
            where
                F: Fn(HookInput, Option<String>, HookContext) -> Fut + Send + Sync + 'static,
                Fut: std::future::Future<Output = HookJsonOutput> + Send + 'static,
            {
                let wrapper = move |input: HookInput, tool_use_id: Option<String>, context: HookContext| {
                    Box::pin(hook_fn(input, tool_use_id, context)) as BoxFuture<'static, HookJsonOutput>
                };
                self.add_hook(HookEvent::$event, Some(matcher), wrapper);
            }
        }
    };

    // Generate method without matcher support
    (@no_matcher $event:ident, $method_name:ident, $doc:expr) => {
        #[doc = $doc]
        pub fn $method_name<F, Fut>(&mut self, hook_fn: F)
        where
            F: Fn(HookInput, Option<String>, HookContext) -> Fut + Send + Sync + 'static,
            Fut: std::future::Future<Output = HookJsonOutput> + Send + 'static,
        {
            let wrapper = move |input: HookInput, tool_use_id: Option<String>, context: HookContext| {
                Box::pin(hook_fn(input, tool_use_id, context)) as BoxFuture<'static, HookJsonOutput>
            };
            self.add_hook(HookEvent::$event, None::<String>, wrapper);
        }
    };
}

/// User-friendly hooks builder
///
/// This provides a convenient API for registering hooks.
///
/// # Example
/// ```no_run
/// use claude_agent_sdk::{Hooks, HookInput, HookContext, HookJsonOutput};
///
/// async fn my_hook(input: HookInput, tool_use_id: Option<String>, context: HookContext) -> HookJsonOutput {
///     HookJsonOutput::Sync(Default::default())
/// }
///
/// let mut hooks = Hooks::new();
/// hooks.add_pre_tool_use(my_hook); // Matches all tools
/// hooks.add_pre_tool_use_with_matcher("Bash", my_hook); // Only Bash tool
/// ```
#[derive(Default)]
pub struct Hooks {
    hooks: HashMap<HookEvent, Vec<HookMatcher>>,
}

impl Hooks {
    /// Create a new empty hooks builder
    pub fn new() -> Self {
        Self::default()
    }

    /// Convert to the internal HashMap format used by ClaudeAgentOptions
    pub fn build(self) -> HashMap<HookEvent, Vec<HookMatcher>> {
        self.hooks
    }

    /// Add a hook for a specific event and optional matcher (internal method)
    ///
    /// # Arguments
    /// * `event` - The hook event type
    /// * `matcher` - Optional matcher (None for all tools, Some("ToolName") for specific tool)
    /// * `hook_fn` - The hook function to call
    fn add_hook<F>(&mut self, event: HookEvent, matcher: Option<impl Into<String>>, hook_fn: F)
    where
        F: Fn(HookInput, Option<String>, HookContext) -> BoxFuture<'static, HookJsonOutput>
            + Send
            + Sync
            + 'static,
    {
        let matcher_string = matcher.map(|m| m.into());
        let hook_callback = Arc::new(hook_fn);

        self.hooks.entry(event).or_default().push(HookMatcher {
            matcher: matcher_string,
            hooks: vec![hook_callback],
            timeout: None,
        });
    }

    // Generate all hook methods
    generate_hook_methods! {
        with_matcher: {
            PreToolUse => add_pre_tool_use: "Add a PreToolUse hook that fires before tool execution.",
            PostToolUse => add_post_tool_use: "Add a PostToolUse hook that fires after tool execution.",
        },
        without_matcher: {
            UserPromptSubmit => add_user_prompt_submit: "Add a UserPromptSubmit hook that fires when user submits a prompt.",
            Stop => add_stop: "Add a Stop hook that fires when execution stops.",
            SubagentStop => add_subagent_stop: "Add a SubagentStop hook that fires when a subagent stops.",
            PreCompact => add_pre_compact: "Add a PreCompact hook that fires before conversation compaction.",
        },
    }
}