ai-agent-sdk 0.5.0

Idiomatic agent sdk inspired by the claude code source leak
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
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
//! Permission management for agent tool access control.
//!
//! This module provides a permission system similar to claude code's permissions,
//! with support for permission modes, rules, and decisions.

use serde::{Deserialize, Serialize};

/// Permission behavior - what to do when a tool is used
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum PermissionBehavior {
    /// Always allow the tool
    Allow,
    /// Always deny the tool
    Deny,
    /// Ask the user for permission
    #[default]
    Ask,
}

impl PermissionBehavior {
    /// Get string representation
    pub fn as_str(&self) -> &'static str {
        match self {
            PermissionBehavior::Allow => "allow",
            PermissionBehavior::Deny => "deny",
            PermissionBehavior::Ask => "ask",
        }
    }
}

/// Permission mode - controls how permissions are handled globally
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum PermissionMode {
    /// Default mode - ask for permission
    #[default]
    Default,
    /// Accept edits without asking
    AcceptEdits,
    /// Bypass all permission checks
    Bypass,
    /// Deny all without asking
    DontAsk,
    /// Plan mode - for planning operations
    Plan,
    /// Auto mode - automatically decide based on context
    Auto,
}

/// Source of a permission rule
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PermissionRuleSource {
    /// User-level settings (~/.ai/)
    UserSettings,
    /// Project-level settings (./.ai/)
    ProjectSettings,
    /// Local settings (./.ai.local/)
    LocalSettings,
    /// From CLI arguments
    CliArg,
    /// From command/session
    Session,
    /// From policy
    Policy,
    /// From flag settings
    FlagSettings,
}

/// A permission rule - specifies behavior for a tool
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PermissionRule {
    /// Source of this rule
    pub source: PermissionRuleSource,
    /// Behavior (allow/deny/ask)
    pub behavior: PermissionBehavior,
    /// The tool name this rule applies to
    pub tool_name: String,
    /// Optional content pattern to match
    pub rule_content: Option<String>,
}

impl PermissionRule {
    /// Create a new permission rule
    pub fn new(tool_name: &str, behavior: PermissionBehavior) -> Self {
        Self {
            source: PermissionRuleSource::UserSettings,
            behavior,
            tool_name: tool_name.to_string(),
            rule_content: None,
        }
    }

    /// Create a rule with content pattern
    pub fn with_content(tool_name: &str, behavior: PermissionBehavior, content: &str) -> Self {
        Self {
            source: PermissionRuleSource::UserSettings,
            behavior,
            tool_name: tool_name.to_string(),
            rule_content: Some(content.to_string()),
        }
    }

    /// Create an allow rule
    pub fn allow(tool_name: &str) -> Self {
        Self::new(tool_name, PermissionBehavior::Allow)
    }

    /// Create a deny rule
    pub fn deny(tool_name: &str) -> Self {
        Self::new(tool_name, PermissionBehavior::Deny)
    }

    /// Create an ask rule
    pub fn ask(tool_name: &str) -> Self {
        Self::new(tool_name, PermissionBehavior::Ask)
    }
}

/// Permission metadata for a tool request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionMetadata {
    /// Tool name
    pub tool_name: String,
    /// Tool description
    pub description: Option<String>,
    /// The input/arguments to the tool
    pub input: Option<serde_json::Value>,
    /// Current working directory
    pub cwd: Option<String>,
}

impl PermissionMetadata {
    /// Create new metadata
    pub fn new(tool_name: &str) -> Self {
        Self {
            tool_name: tool_name.to_string(),
            description: None,
            input: None,
            cwd: None,
        }
    }

    /// Set description
    pub fn with_description(mut self, description: &str) -> Self {
        self.description = Some(description.to_string());
        self
    }

    /// Set input
    pub fn with_input(mut self, input: serde_json::Value) -> Self {
        self.input = Some(input);
        self
    }

    /// Set cwd
    pub fn with_cwd(mut self, cwd: &str) -> Self {
        self.cwd = Some(cwd.to_string());
        self
    }
}

/// Reason for a permission decision
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum PermissionDecisionReason {
    /// Matched a permission rule
    Rule { rule: PermissionRule },
    /// Determined by permission mode
    Mode { mode: PermissionMode },
    /// From a hook
    Hook {
        hook_name: String,
        reason: Option<String>,
    },
    /// Sandbox override
    SandboxOverride { reason: String },
    /// Safety check failed
    SafetyCheck { reason: String },
    /// Other reason
    Other { reason: String },
}

/// Result when permission is allowed
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionAllowDecision {
    pub behavior: PermissionBehavior,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_input: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_modified: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub decision_reason: Option<PermissionDecisionReason>,
}

impl PermissionAllowDecision {
    /// Create an allow decision
    pub fn new() -> Self {
        Self {
            behavior: PermissionBehavior::Allow,
            updated_input: None,
            user_modified: None,
            decision_reason: None,
        }
    }

    /// Create with reason
    pub fn with_reason(mut self, reason: PermissionDecisionReason) -> Self {
        self.decision_reason = Some(reason);
        self
    }
}

impl Default for PermissionAllowDecision {
    fn default() -> Self {
        Self::new()
    }
}

/// Result when permission should be asked
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionAskDecision {
    pub behavior: PermissionBehavior,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_input: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub decision_reason: Option<PermissionDecisionReason>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blocked_path: Option<String>,
}

impl PermissionAskDecision {
    /// Create an ask decision with message
    pub fn new(message: &str) -> Self {
        Self {
            behavior: PermissionBehavior::Ask,
            message: message.to_string(),
            updated_input: None,
            decision_reason: None,
            blocked_path: None,
        }
    }

    /// Create with reason
    pub fn with_reason(mut self, reason: PermissionDecisionReason) -> Self {
        self.decision_reason = Some(reason);
        self
    }

    /// Create with blocked path
    pub fn with_blocked_path(mut self, path: &str) -> Self {
        self.blocked_path = Some(path.to_string());
        self
    }
}

/// Result when permission is denied
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionDenyDecision {
    pub behavior: PermissionBehavior,
    pub message: String,
    pub decision_reason: PermissionDecisionReason,
}

impl PermissionDenyDecision {
    /// Create a deny decision with message
    pub fn new(message: &str, reason: PermissionDecisionReason) -> Self {
        Self {
            behavior: PermissionBehavior::Deny,
            message: message.to_string(),
            decision_reason: reason,
        }
    }
}

/// A permission decision - allow, ask, or deny
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "behavior", rename_all = "lowercase")]
pub enum PermissionDecision {
    Allow(PermissionAllowDecision),
    Ask(PermissionAskDecision),
    Deny(PermissionDenyDecision),
}

impl PermissionDecision {
    /// Check if allowed
    pub fn is_allowed(&self) -> bool {
        matches!(self, PermissionDecision::Allow(_))
    }

    /// Check if denied
    pub fn is_denied(&self) -> bool {
        matches!(self, PermissionDecision::Deny(_))
    }

    /// Check if asking
    pub fn is_ask(&self) -> bool {
        matches!(self, PermissionDecision::Ask(_))
    }

    /// Get the message if present
    pub fn message(&self) -> Option<&str> {
        match self {
            PermissionDecision::Allow(_) => None,
            PermissionDecision::Ask(d) => Some(&d.message),
            PermissionDecision::Deny(d) => Some(&d.message),
        }
    }
}

/// Permission result with additional passthrough option
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "behavior", rename_all = "lowercase")]
pub enum PermissionResult {
    Allow(PermissionAllowDecision),
    Ask(PermissionAskDecision),
    Deny(PermissionDenyDecision),
    /// Passthrough - allow but log/notify
    Passthrough {
        message: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        decision_reason: Option<PermissionDecisionReason>,
    },
}

impl PermissionResult {
    /// Convert to decision
    pub fn to_decision(self) -> Option<PermissionDecision> {
        match self {
            PermissionResult::Allow(d) => Some(PermissionDecision::Allow(d)),
            PermissionResult::Ask(d) => Some(PermissionDecision::Ask(d)),
            PermissionResult::Deny(d) => Some(PermissionDecision::Deny(d)),
            PermissionResult::Passthrough { .. } => None,
        }
    }

    /// Check if allowed (including passthrough)
    pub fn is_allowed(&self) -> bool {
        matches!(
            self,
            PermissionResult::Allow(_) | PermissionResult::Passthrough { .. }
        )
    }

    /// Check if denied
    pub fn is_denied(&self) -> bool {
        matches!(self, PermissionResult::Deny(_))
    }

    /// Check if asking
    pub fn is_ask(&self) -> bool {
        matches!(self, PermissionResult::Ask(_))
    }

    /// Get the message
    pub fn message(&self) -> Option<&str> {
        match self {
            PermissionResult::Allow(_) => None,
            PermissionResult::Ask(d) => Some(&d.message),
            PermissionResult::Deny(d) => Some(&d.message),
            PermissionResult::Passthrough { message, .. } => Some(message),
        }
    }
}

/// Permission context for checking tool access
#[derive(Debug, Clone, Default)]
pub struct PermissionContext {
    /// Current permission mode
    pub mode: PermissionMode,
    /// Always allow rules
    pub allow_rules: Vec<PermissionRule>,
    /// Always deny rules
    pub deny_rules: Vec<PermissionRule>,
    /// Always ask rules
    pub ask_rules: Vec<PermissionRule>,
}

impl PermissionContext {
    /// Create a new permission context
    pub fn new() -> Self {
        Self::default()
    }

    /// Set permission mode
    pub fn with_mode(mut self, mode: PermissionMode) -> Self {
        self.mode = mode;
        self
    }

    /// Add an allow rule
    pub fn with_allow_rule(mut self, rule: PermissionRule) -> Self {
        self.allow_rules.push(rule);
        self
    }

    /// Add a deny rule
    pub fn with_deny_rule(mut self, rule: PermissionRule) -> Self {
        self.deny_rules.push(rule);
        self
    }

    /// Add an ask rule
    pub fn with_ask_rule(mut self, rule: PermissionRule) -> Self {
        self.ask_rules.push(rule);
        self
    }

    /// Check if a tool is allowed
    pub fn check_tool(
        &self,
        tool_name: &str,
        input: Option<&serde_json::Value>,
    ) -> PermissionResult {
        // Check deny rules first
        for rule in &self.deny_rules {
            if rule.tool_name == tool_name {
                return PermissionResult::Deny(PermissionDenyDecision::new(
                    &format!("Tool '{}' is denied by rule", tool_name),
                    PermissionDecisionReason::Rule { rule: rule.clone() },
                ));
            }
        }

        // Check allow rules
        for rule in &self.allow_rules {
            if rule.tool_name == tool_name {
                // Check content if specified
                if let Some(content) = &rule.rule_content {
                    if let Some(input) = input {
                        let input_str = input.to_string();
                        if input_str.contains(content) {
                            return PermissionResult::Allow(
                                PermissionAllowDecision::new().with_reason(
                                    PermissionDecisionReason::Rule { rule: rule.clone() },
                                ),
                            );
                        }
                    }
                } else {
                    return PermissionResult::Allow(
                        PermissionAllowDecision::new()
                            .with_reason(PermissionDecisionReason::Rule { rule: rule.clone() }),
                    );
                }
            }
        }

        // Check ask rules
        for rule in &self.ask_rules {
            if rule.tool_name == tool_name {
                return PermissionResult::Ask(
                    PermissionAskDecision::new(&format!(
                        "Tool '{}' requires permission",
                        tool_name
                    ))
                    .with_reason(PermissionDecisionReason::Rule { rule: rule.clone() }),
                );
            }
        }

        // Check permission mode
        match self.mode {
            PermissionMode::Bypass => {
                return PermissionResult::Allow(PermissionAllowDecision::new().with_reason(
                    PermissionDecisionReason::Mode {
                        mode: PermissionMode::Bypass,
                    },
                ));
            }
            PermissionMode::DontAsk => {
                return PermissionResult::Deny(PermissionDenyDecision::new(
                    "Permission mode is 'dontAsk'",
                    PermissionDecisionReason::Mode {
                        mode: PermissionMode::DontAsk,
                    },
                ));
            }
            PermissionMode::AcceptEdits => {
                // Allow edit tools
                if tool_name == "Write" || tool_name == "Edit" || tool_name == "Bash" {
                    return PermissionResult::Allow(PermissionAllowDecision::new().with_reason(
                        PermissionDecisionReason::Mode {
                            mode: PermissionMode::AcceptEdits,
                        },
                    ));
                }
            }
            _ => {}
        }

        // Default: ask
        PermissionResult::Ask(
            PermissionAskDecision::new(&format!("Permission required to use {}", tool_name))
                .with_reason(PermissionDecisionReason::Mode { mode: self.mode }),
        )
    }
}

/// Callback type for permission checks
pub type PermissionCallback =
    Box<dyn Fn(PermissionMetadata, PermissionResult) -> PermissionResult + Send + Sync>;

/// Permission handler with callback support
pub struct PermissionHandler {
    context: PermissionContext,
    callback: Option<PermissionCallback>,
}

impl PermissionHandler {
    /// Create a new permission handler
    pub fn new(context: PermissionContext) -> Self {
        Self {
            context,
            callback: None,
        }
    }

    /// Create with a callback
    pub fn with_callback(context: PermissionContext, callback: PermissionCallback) -> Self {
        Self {
            context,
            callback: Some(callback),
        }
    }

    /// Check permission for a tool
    pub fn check(&self, metadata: PermissionMetadata) -> PermissionResult {
        let result = self
            .context
            .check_tool(&metadata.tool_name, metadata.input.as_ref());

        // If there's a callback, let it override the decision
        if let Some(callback) = &self.callback {
            return callback(metadata, result);
        }

        result
    }

    /// Check if tool is allowed
    pub fn is_allowed(&self, metadata: &PermissionMetadata) -> bool {
        self.check(metadata.clone()).is_allowed()
    }
}

impl PermissionHandler {
    /// Create a default permission handler
    pub fn default() -> Self {
        Self::new(PermissionContext::default())
    }
}

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

    // =====================================================================
    // PermissionRule Tests
    // =====================================================================

    #[test]
    fn test_permission_rule_allow() {
        let rule = PermissionRule::allow("Bash");
        assert_eq!(rule.tool_name, "Bash");
        assert_eq!(rule.behavior, PermissionBehavior::Allow);
        assert_eq!(rule.source, PermissionRuleSource::UserSettings);
        assert!(rule.rule_content.is_none());
    }

    #[test]
    fn test_permission_rule_deny() {
        let rule = PermissionRule::deny("Edit");
        assert_eq!(rule.tool_name, "Edit");
        assert_eq!(rule.behavior, PermissionBehavior::Deny);
    }

    #[test]
    fn test_permission_rule_ask() {
        let rule = PermissionRule::ask("Grep");
        assert_eq!(rule.tool_name, "Grep");
        assert_eq!(rule.behavior, PermissionBehavior::Ask);
    }

    #[test]
    fn test_permission_rule_with_content() {
        let rule = PermissionRule::with_content("Bash", PermissionBehavior::Allow, "ls");
        assert_eq!(rule.tool_name, "Bash");
        assert_eq!(rule.behavior, PermissionBehavior::Allow);
        assert_eq!(rule.rule_content, Some("ls".to_string()));
    }

    #[test]
    fn test_permission_rule_new() {
        let rule = PermissionRule::new("Read", PermissionBehavior::Allow);
        assert_eq!(rule.tool_name, "Read");
        assert_eq!(rule.behavior, PermissionBehavior::Allow);
    }

    #[test]
    fn test_permission_rule_with_source() {
        let rule = PermissionRule {
            source: PermissionRuleSource::CliArg,
            behavior: PermissionBehavior::Allow,
            tool_name: "Bash".to_string(),
            rule_content: None,
        };
        assert_eq!(rule.source, PermissionRuleSource::CliArg);
    }

    // =====================================================================
    // PermissionMetadata Tests
    // =====================================================================

    #[test]
    fn test_permission_metadata() {
        let meta = PermissionMetadata::new("Bash");
        assert_eq!(meta.tool_name, "Bash");
        assert!(meta.description.is_none());
        assert!(meta.input.is_none());
        assert!(meta.cwd.is_none());
    }

    #[test]
    fn test_permission_metadata_with_description() {
        let meta = PermissionMetadata::new("Bash").with_description("Run shell commands");
        assert_eq!(meta.description, Some("Run shell commands".to_string()));
    }

    #[test]
    fn test_permission_metadata_with_input() {
        let meta = PermissionMetadata::new("Bash").with_input(serde_json::json!({"command": "ls"}));
        assert!(meta.input.is_some());
    }

    #[test]
    fn test_permission_metadata_with_cwd() {
        let meta = PermissionMetadata::new("Bash").with_cwd("/home/user");
        assert_eq!(meta.cwd, Some("/home/user".to_string()));
    }

    // =====================================================================
    // PermissionContext Tests - Deny Rules
    // =====================================================================

    #[test]
    fn test_permission_context_deny_rule() {
        let ctx = PermissionContext::new().with_deny_rule(PermissionRule::deny("Bash"));

        let result = ctx.check_tool("Bash", None);
        assert!(result.is_denied());
    }

    #[test]
    fn test_permission_context_deny_rule_not_matching() {
        let ctx = PermissionContext::new().with_deny_rule(PermissionRule::deny("Bash"));

        // Different tool should not be denied
        let result = ctx.check_tool("Read", None);
        assert!(!result.is_denied());
    }

    #[test]
    fn test_permission_context_multiple_deny_rules() {
        let ctx = PermissionContext::new()
            .with_deny_rule(PermissionRule::deny("Bash"))
            .with_deny_rule(PermissionRule::deny("Edit"));

        assert!(ctx.check_tool("Bash", None).is_denied());
        assert!(ctx.check_tool("Edit", None).is_denied());
        assert!(!ctx.check_tool("Read", None).is_denied());
    }

    // =====================================================================
    // PermissionContext Tests - Allow Rules
    // =====================================================================

    #[test]
    fn test_permission_context_allow_rule() {
        let ctx = PermissionContext::new().with_allow_rule(PermissionRule::allow("Read"));

        let result = ctx.check_tool("Read", None);
        assert!(result.is_allowed());
    }

    #[test]
    fn test_permission_context_allow_rule_with_content_match() {
        let ctx = PermissionContext::new().with_allow_rule(PermissionRule::with_content(
            "Bash",
            PermissionBehavior::Allow,
            "ls",
        ));

        let input = serde_json::json!({"command": "ls -la"});
        let result = ctx.check_tool("Bash", Some(&input));
        assert!(result.is_allowed());
    }

    #[test]
    fn test_permission_context_allow_rule_with_content_no_match() {
        let ctx = PermissionContext::new().with_allow_rule(PermissionRule::with_content(
            "Bash",
            PermissionBehavior::Allow,
            "ls",
        ));

        let input = serde_json::json!({"command": "rm -rf /"});
        let result = ctx.check_tool("Bash", Some(&input));
        assert!(!result.is_allowed());
    }

    #[test]
    fn test_permission_context_allow_rule_no_input() {
        // When rule has content but no input provided, should not match
        let ctx = PermissionContext::new().with_allow_rule(PermissionRule::with_content(
            "Bash",
            PermissionBehavior::Allow,
            "ls",
        ));

        let result = ctx.check_tool("Bash", None);
        // No input means content can't match, falls through to default
        assert!(!result.is_allowed());
    }

    // =====================================================================
    // PermissionContext Tests - Ask Rules
    // =====================================================================

    #[test]
    fn test_permission_context_ask_rule() {
        let ctx = PermissionContext::new().with_ask_rule(PermissionRule::ask("Grep"));

        let result = ctx.check_tool("Grep", None);
        assert!(result.is_ask());
    }

    #[test]
    fn test_permission_context_ask_rule_not_matching() {
        let ctx = PermissionContext::new()
            .with_mode(PermissionMode::Bypass) // Use bypass mode to avoid default ask
            .with_ask_rule(PermissionRule::ask("Grep"));

        let result = ctx.check_tool("Read", None);
        // With bypass mode and no matching rule, should be allowed (not ask)
        assert!(!result.is_ask());
    }

    // =====================================================================
    // PermissionContext Tests - Rule Priority
    // =====================================================================

    #[test]
    fn test_permission_context_deny_overrides_allow() {
        // Deny should take precedence over allow
        let ctx = PermissionContext::new()
            .with_allow_rule(PermissionRule::allow("Bash"))
            .with_deny_rule(PermissionRule::deny("Bash"));

        let result = ctx.check_tool("Bash", None);
        assert!(result.is_denied());
    }

    #[test]
    fn test_permission_context_allow_overrides_default() {
        let ctx = PermissionContext::new()
            .with_mode(PermissionMode::DontAsk) // Default deny
            .with_allow_rule(PermissionRule::allow("Read"));

        let result = ctx.check_tool("Read", None);
        assert!(result.is_allowed());
    }

    // =====================================================================
    // PermissionContext Tests - Permission Modes
    // =====================================================================

    #[test]
    fn test_permission_mode_default() {
        let ctx = PermissionContext::new().with_mode(PermissionMode::Default);
        let result = ctx.check_tool("Bash", None);
        // Default mode asks for permission
        assert!(result.is_ask());
    }

    #[test]
    fn test_permission_mode_bypass() {
        let ctx = PermissionContext::new().with_mode(PermissionMode::Bypass);
        let result = ctx.check_tool("Bash", None);
        assert!(result.is_allowed());
    }

    #[test]
    fn test_permission_mode_bypass_deny_rule_still_applies() {
        // Bypass mode can still be overridden by deny rules
        let ctx = PermissionContext::new()
            .with_mode(PermissionMode::Bypass)
            .with_deny_rule(PermissionRule::deny("Bash"));

        let result = ctx.check_tool("Bash", None);
        assert!(result.is_denied());
    }

    #[test]
    fn test_permission_mode_dont_ask() {
        let ctx = PermissionContext::new().with_mode(PermissionMode::DontAsk);
        let result = ctx.check_tool("Bash", None);
        assert!(result.is_denied());
    }

    #[test]
    fn test_permission_mode_accept_edits_allows_write() {
        let ctx = PermissionContext::new().with_mode(PermissionMode::AcceptEdits);
        let result = ctx.check_tool("Write", None);
        assert!(result.is_allowed());
    }

    #[test]
    fn test_permission_mode_accept_edits_allows_edit() {
        let ctx = PermissionContext::new().with_mode(PermissionMode::AcceptEdits);
        let result = ctx.check_tool("Edit", None);
        assert!(result.is_allowed());
    }

    #[test]
    fn test_permission_mode_accept_edits_allows_bash() {
        let ctx = PermissionContext::new().with_mode(PermissionMode::AcceptEdits);
        let result = ctx.check_tool("Bash", None);
        assert!(result.is_allowed());
    }

    #[test]
    fn test_permission_mode_accept_edits_denies_read() {
        let ctx = PermissionContext::new().with_mode(PermissionMode::AcceptEdits);
        let result = ctx.check_tool("Read", None);
        // AcceptEdits allows write/edit/bash, but for other tools defaults to ask
        assert!(result.is_ask());
    }

    #[test]
    fn test_permission_mode_plan() {
        let ctx = PermissionContext::new().with_mode(PermissionMode::Plan);
        let result = ctx.check_tool("Bash", None);
        // Plan mode should ask
        assert!(result.is_ask());
    }

    #[test]
    fn test_permission_mode_auto() {
        let ctx = PermissionContext::new().with_mode(PermissionMode::Auto);
        let result = ctx.check_tool("Bash", None);
        // Auto mode should ask by default
        assert!(result.is_ask());
    }

    // =====================================================================
    // PermissionDecisionReason Tests
    // =====================================================================

    #[test]
    fn test_permission_decision_reason_rule() {
        let reason = PermissionDecisionReason::Rule {
            rule: PermissionRule::allow("Bash"),
        };
        match reason {
            PermissionDecisionReason::Rule { rule } => {
                assert_eq!(rule.tool_name, "Bash");
            }
            _ => panic!("Expected Rule reason"),
        }
    }

    #[test]
    fn test_permission_decision_reason_mode() {
        let reason = PermissionDecisionReason::Mode {
            mode: PermissionMode::Bypass,
        };
        match reason {
            PermissionDecisionReason::Mode { mode } => {
                assert_eq!(mode, PermissionMode::Bypass);
            }
            _ => panic!("Expected Mode reason"),
        }
    }

    #[test]
    fn test_permission_decision_reason_hook() {
        let reason = PermissionDecisionReason::Hook {
            hook_name: "test_hook".to_string(),
            reason: Some("blocked".to_string()),
        };
        match reason {
            PermissionDecisionReason::Hook { hook_name, reason } => {
                assert_eq!(hook_name, "test_hook");
                assert_eq!(reason, Some("blocked".to_string()));
            }
            _ => panic!("Expected Hook reason"),
        }
    }

    #[test]
    fn test_permission_decision_reason_other() {
        let reason = PermissionDecisionReason::Other {
            reason: "custom reason".to_string(),
        };
        match reason {
            PermissionDecisionReason::Other { reason } => {
                assert_eq!(reason, "custom reason");
            }
            _ => panic!("Expected Other reason"),
        }
    }

    // =====================================================================
    // PermissionDecision Tests
    // =====================================================================

    #[test]
    fn test_permission_decision_is_allowed() {
        let decision = PermissionDecision::Allow(PermissionAllowDecision::new());
        assert!(decision.is_allowed());
        assert!(!decision.is_denied());
        assert!(!decision.is_ask());
    }

    #[test]
    fn test_permission_decision_is_denied() {
        let decision = PermissionDecision::Deny(PermissionDenyDecision::new(
            "denied",
            PermissionDecisionReason::Other {
                reason: "test".to_string(),
            },
        ));
        assert!(!decision.is_allowed());
        assert!(decision.is_denied());
        assert!(!decision.is_ask());
    }

    #[test]
    fn test_permission_decision_is_ask() {
        let decision = PermissionDecision::Ask(PermissionAskDecision::new("ask"));
        assert!(!decision.is_allowed());
        assert!(!decision.is_denied());
        assert!(decision.is_ask());
    }

    #[test]
    fn test_permission_decision_message() {
        let decision = PermissionDecision::Ask(PermissionAskDecision::new("please allow"));
        assert_eq!(decision.message(), Some("please allow"));

        let decision = PermissionDecision::Allow(PermissionAllowDecision::new());
        assert_eq!(decision.message(), None);
    }

    // =====================================================================
    // PermissionResult Tests
    // =====================================================================

    #[test]
    fn test_permission_result_is_allowed() {
        let result = PermissionResult::Allow(PermissionAllowDecision::new());
        assert!(result.is_allowed());
    }

    #[test]
    fn test_permission_result_passthrough_is_allowed() {
        let result = PermissionResult::Passthrough {
            message: "logged".to_string(),
            decision_reason: None,
        };
        assert!(result.is_allowed());
    }

    #[test]
    fn test_permission_result_is_denied() {
        let result = PermissionResult::Deny(PermissionDenyDecision::new(
            "denied",
            PermissionDecisionReason::Other {
                reason: "test".to_string(),
            },
        ));
        assert!(result.is_denied());
    }

    #[test]
    fn test_permission_result_is_ask() {
        let result = PermissionResult::Ask(PermissionAskDecision::new("ask"));
        assert!(result.is_ask());
    }

    #[test]
    fn test_permission_result_message() {
        let result = PermissionResult::Ask(PermissionAskDecision::new("ask me"));
        assert_eq!(result.message(), Some("ask me"));

        let result = PermissionResult::Passthrough {
            message: "passthrough".to_string(),
            decision_reason: None,
        };
        assert_eq!(result.message(), Some("passthrough"));
    }

    #[test]
    fn test_permission_result_to_decision() {
        let result = PermissionResult::Allow(PermissionAllowDecision::new());
        let decision = result.to_decision();
        assert!(decision.is_some());
        assert!(decision.unwrap().is_allowed());

        let result = PermissionResult::Passthrough {
            message: "test".to_string(),
            decision_reason: None,
        };
        let decision = result.to_decision();
        assert!(decision.is_none());
    }

    // =====================================================================
    // PermissionHandler Tests
    // =====================================================================

    #[test]
    fn test_permission_handler_default() {
        let handler = PermissionHandler::default();
        let meta = PermissionMetadata::new("Bash");
        let result = handler.check(meta);
        // Default context should ask
        assert!(result.is_ask());
    }

    #[test]
    fn test_permission_handler_with_context() {
        let ctx = PermissionContext::new().with_mode(PermissionMode::Bypass);
        let handler = PermissionHandler::new(ctx);
        let meta = PermissionMetadata::new("Bash");
        let result = handler.check(meta);
        assert!(result.is_allowed());
    }

    #[test]
    fn test_permission_handler_is_allowed() {
        let handler = PermissionHandler::new(
            PermissionContext::new().with_allow_rule(PermissionRule::allow("Read")),
        );
        let meta = PermissionMetadata::new("Read");
        assert!(handler.is_allowed(&meta));

        let meta = PermissionMetadata::new("Bash");
        assert!(!handler.is_allowed(&meta));
    }

    // =====================================================================
    // Edge Cases
    // =====================================================================

    #[test]
    fn test_permission_context_unknown_tool_defaults_to_ask() {
        let ctx = PermissionContext::new();
        let result = ctx.check_tool("UnknownTool", None);
        assert!(result.is_ask());
    }

    #[test]
    fn test_permission_context_empty_rules() {
        let ctx = PermissionContext::new();
        let result = ctx.check_tool("Read", None);
        // No rules, default mode asks
        assert!(result.is_ask());
    }

    #[test]
    fn test_permission_metadata_all_fields() {
        let meta = PermissionMetadata::new("Bash")
            .with_description("Run commands")
            .with_input(serde_json::json!({"command": "ls"}))
            .with_cwd("/home/user");

        assert_eq!(meta.tool_name, "Bash");
        assert_eq!(meta.description, Some("Run commands".to_string()));
        assert!(meta.input.is_some());
        assert_eq!(meta.cwd, Some("/home/user".to_string()));
    }

    #[test]
    fn test_permission_mode_all_variants() {
        let modes = vec![
            PermissionMode::Default,
            PermissionMode::AcceptEdits,
            PermissionMode::Bypass,
            PermissionMode::DontAsk,
            PermissionMode::Plan,
            PermissionMode::Auto,
        ];

        for mode in modes {
            let ctx = PermissionContext::new().with_mode(mode);
            let result = ctx.check_tool("Read", None);
            // All modes should return some result
            assert!(result.is_allowed() || result.is_denied() || result.is_ask());
        }
    }

    #[test]
    fn test_permission_behavior_all_variants() {
        assert_eq!(PermissionBehavior::Allow.as_str(), "allow");
        assert_eq!(PermissionBehavior::Deny.as_str(), "deny");
        assert_eq!(PermissionBehavior::Ask.as_str(), "ask");
    }

    #[test]
    fn test_permission_rule_source_all_variants() {
        // Test each source variant individually
        let rule1 = PermissionRule {
            source: PermissionRuleSource::UserSettings,
            behavior: PermissionBehavior::Allow,
            tool_name: "Test".to_string(),
            rule_content: None,
        };
        assert_eq!(rule1.source, PermissionRuleSource::UserSettings);

        let rule2 = PermissionRule {
            source: PermissionRuleSource::ProjectSettings,
            behavior: PermissionBehavior::Allow,
            tool_name: "Test".to_string(),
            rule_content: None,
        };
        assert_eq!(rule2.source, PermissionRuleSource::ProjectSettings);

        let rule3 = PermissionRule {
            source: PermissionRuleSource::LocalSettings,
            behavior: PermissionBehavior::Allow,
            tool_name: "Test".to_string(),
            rule_content: None,
        };
        assert_eq!(rule3.source, PermissionRuleSource::LocalSettings);

        let rule4 = PermissionRule {
            source: PermissionRuleSource::CliArg,
            behavior: PermissionBehavior::Allow,
            tool_name: "Test".to_string(),
            rule_content: None,
        };
        assert_eq!(rule4.source, PermissionRuleSource::CliArg);

        let rule5 = PermissionRule {
            source: PermissionRuleSource::Session,
            behavior: PermissionBehavior::Allow,
            tool_name: "Test".to_string(),
            rule_content: None,
        };
        assert_eq!(rule5.source, PermissionRuleSource::Session);

        let rule6 = PermissionRule {
            source: PermissionRuleSource::Policy,
            behavior: PermissionBehavior::Allow,
            tool_name: "Test".to_string(),
            rule_content: None,
        };
        assert_eq!(rule6.source, PermissionRuleSource::Policy);

        let rule7 = PermissionRule {
            source: PermissionRuleSource::FlagSettings,
            behavior: PermissionBehavior::Allow,
            tool_name: "Test".to_string(),
            rule_content: None,
        };
        assert_eq!(rule7.source, PermissionRuleSource::FlagSettings);
    }

    #[test]
    fn test_permission_decision_serialization() {
        let decision = PermissionDecision::Allow(PermissionAllowDecision::new());
        let json = serde_json::to_string(&decision).unwrap();
        assert!(json.contains("\"allow\""));

        let decision = PermissionDecision::Ask(PermissionAskDecision::new("test"));
        let json = serde_json::to_string(&decision).unwrap();
        assert!(json.contains("\"ask\""));

        let decision = PermissionDecision::Deny(PermissionDenyDecision::new(
            "test",
            PermissionDecisionReason::Other {
                reason: "test".to_string(),
            },
        ));
        let json = serde_json::to_string(&decision).unwrap();
        assert!(json.contains("\"deny\""));
    }

    #[test]
    fn test_permission_result_serialization() {
        let result = PermissionResult::Allow(PermissionAllowDecision::new());
        let json = serde_json::to_string(&result).unwrap();
        assert!(json.contains("\"allow\""));

        let result = PermissionResult::Ask(PermissionAskDecision::new("test"));
        let json = serde_json::to_string(&result).unwrap();
        assert!(json.contains("\"ask\""));

        let result = PermissionResult::Deny(PermissionDenyDecision::new(
            "test",
            PermissionDecisionReason::Other {
                reason: "test".to_string(),
            },
        ));
        let json = serde_json::to_string(&result).unwrap();
        assert!(json.contains("\"deny\""));

        let result = PermissionResult::Passthrough {
            message: "test".to_string(),
            decision_reason: None,
        };
        let json = serde_json::to_string(&result).unwrap();
        assert!(json.contains("\"passthrough\""));
    }

    #[test]
    fn test_permission_rule_serialization() {
        let rule = PermissionRule::allow("Bash");
        let json = serde_json::to_string(&rule).unwrap();
        assert!(json.contains("Bash"));
        assert!(json.contains("allow"));
    }

    #[test]
    fn test_permission_context_serialization() {
        let ctx = PermissionContext::new()
            .with_mode(PermissionMode::Bypass)
            .with_allow_rule(PermissionRule::allow("Read"));

        // Context should be cloneable
        let ctx2 = ctx.clone();
        let result = ctx2.check_tool("Read", None);
        assert!(result.is_allowed());
    }

    #[test]
    fn test_permission_ask_decision_with_blocked_path() {
        let decision = PermissionAskDecision::new("blocked").with_blocked_path("/etc/passwd");
        assert_eq!(decision.blocked_path, Some("/etc/passwd".to_string()));
    }

    #[test]
    fn test_permission_allow_decision_with_reason() {
        let reason = PermissionDecisionReason::Mode {
            mode: PermissionMode::Bypass,
        };
        let decision = PermissionAllowDecision::new().with_reason(reason.clone());
        assert_eq!(decision.decision_reason, Some(reason));
    }

    #[test]
    fn test_permission_deny_decision_with_reason() {
        let reason = PermissionDecisionReason::Other {
            reason: "not allowed".to_string(),
        };
        let decision = PermissionDenyDecision::new("denied", reason.clone());
        assert_eq!(decision.decision_reason, reason);
    }
}