claude-code-client-sdk 0.1.46

Rust SDK for integrating Claude Code as a subprocess with typed APIs
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
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
//! Core data types for the Claude Code SDK.
//!
//! This module defines all the configuration, message, and permission types used
//! throughout the SDK. These types correspond to the Python SDK's type definitions
//! documented at <https://platform.claude.com/docs/en/agent-sdk/python>.

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

use futures::future::BoxFuture;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;

use crate::errors::Error;
use crate::sdk_mcp::McpSdkServer;

/// Permission mode controlling how Claude Code handles tool execution permissions.
///
/// Corresponds to the Python SDK's `PermissionMode` literal type.
///
/// # Variants
///
/// - `Default` — Standard permission behavior; Claude prompts for approval on sensitive operations.
/// - `AcceptEdits` — Auto-accept file edits without prompting.
/// - `Plan` — Planning mode; Claude describes actions without executing them.
/// - `BypassPermissions` — Bypass all permission checks. **Use with caution.**
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum PermissionMode {
    /// Standard permission behavior with interactive approval when needed.
    #[serde(rename = "default")]
    Default,
    /// Auto-accept file edits without interactive approval.
    #[serde(rename = "acceptEdits")]
    AcceptEdits,
    /// Planning mode where the model proposes actions instead of executing them.
    #[serde(rename = "plan")]
    Plan,
    /// Bypass all permission checks.
    #[serde(rename = "bypassPermissions")]
    BypassPermissions,
}

/// Controls which filesystem-based configuration sources the SDK loads settings from.
///
/// When `setting_sources` is omitted or `None` in [`ClaudeAgentOptions`], the SDK does
/// **not** load any filesystem settings, providing isolation for SDK applications.
///
/// # Variants
///
/// - `User` — Global user settings (`~/.claude/settings.json`).
/// - `Project` — Shared project settings (`.claude/settings.json`), version controlled.
///   Must be included to load `CLAUDE.md` files.
/// - `Local` — Local project settings (`.claude/settings.local.json`), typically gitignored.
///
/// # Precedence
///
/// When multiple sources are loaded, settings merge with this precedence (highest first):
/// 1. Local settings
/// 2. Project settings
/// 3. User settings
///
/// Programmatic options (e.g., `agents`, `allowed_tools`) always override filesystem settings.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum SettingSource {
    /// Load user-level settings from the home directory.
    User,
    /// Load project-level shared settings.
    Project,
    /// Load local project settings (typically not committed).
    Local,
}

/// Preset configuration for the system prompt.
///
/// Uses Claude Code's built-in system prompt with an optional appended section.
///
/// # Fields
///
/// - `type_` — Must be `"preset"`.
/// - `preset` — Must be `"claude_code"` to use Claude Code's system prompt.
/// - `append` — Optional additional instructions to append to the preset system prompt.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SystemPromptPreset {
    /// Discriminator field for preset prompts (typically `"preset"`).
    #[serde(rename = "type")]
    pub type_: String,
    /// Preset name (typically `"claude_code"`).
    pub preset: String,
    /// Extra instructions appended to the preset prompt.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub append: Option<String>,
}

impl Default for SystemPromptPreset {
    fn default() -> Self {
        Self {
            type_: "preset".to_string(),
            preset: "claude_code".to_string(),
            append: None,
        }
    }
}

/// Preset tools configuration for using Claude Code's default tool set.
///
/// # Fields
///
/// - `type_` — Must be `"preset"`.
/// - `preset` — Must be `"claude_code"` for the default tool set.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolsPreset {
    /// Discriminator field for preset tools (typically `"preset"`).
    #[serde(rename = "type")]
    pub type_: String,
    /// Preset name (typically `"claude_code"`).
    pub preset: String,
}

impl Default for ToolsPreset {
    fn default() -> Self {
        Self {
            type_: "preset".to_string(),
            preset: "claude_code".to_string(),
        }
    }
}

/// System prompt configuration.
///
/// Either provide a custom text prompt or use Claude Code's preset system prompt.
///
/// # Variants
///
/// - `Text` — A custom system prompt string.
/// - `Preset` — Use Claude Code's built-in system prompt via [`SystemPromptPreset`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum SystemPrompt {
    /// Use a custom system prompt string.
    Text(String),
    /// Use Claude Code's preset system prompt.
    Preset(SystemPromptPreset),
}

/// Tools configuration.
///
/// Either provide an explicit list of tool names or use Claude Code's preset tools.
///
/// # Variants
///
/// - `List` — An explicit list of tool name strings.
/// - `Preset` — Use Claude Code's default tool set via [`ToolsPreset`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum ToolsOption {
    /// Explicit list of allowed tool names.
    List(Vec<String>),
    /// Use the default Claude Code tools preset.
    Preset(ToolsPreset),
}

/// Configuration for a programmatically defined subagent.
///
/// Subagents are specialized agents that can be invoked by the main Claude Code agent
/// for specific tasks.
///
/// # Fields
///
/// - `description` — Natural language description of when to use this agent.
/// - `prompt` — The agent's system prompt.
/// - `tools` — Optional list of allowed tool names. If omitted, inherits all tools.
/// - `model` — Optional model override (e.g., `"sonnet"`, `"opus"`, `"haiku"`, `"inherit"`).
///   If omitted, uses the main model.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AgentDefinition {
    /// Human-readable description of when this agent should be used.
    pub description: String,
    /// The sub-agent system prompt.
    pub prompt: String,
    /// Optional tool allowlist for this sub-agent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<String>>,
    /// Optional model override for this sub-agent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
}

/// A rule to add, replace, or remove in a permission update.
///
/// # Fields
///
/// - `tool_name` — The name of the tool this rule applies to.
/// - `rule_content` — Optional rule content string (e.g., a glob pattern or path).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct PermissionRuleValue {
    /// Tool name that this rule applies to.
    pub tool_name: String,
    /// Optional rule body (for example a path or glob).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rule_content: Option<String>,
}

/// Destination for applying a permission update.
///
/// Determines where the permission change is persisted.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum PermissionUpdateDestination {
    /// Persist update to user settings.
    UserSettings,
    /// Persist update to project settings.
    ProjectSettings,
    /// Persist update to local project settings.
    LocalSettings,
    /// Apply update only for the current session.
    Session,
}

/// Behavior for rule-based permission operations.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum PermissionBehavior {
    /// Explicitly allow matching operations.
    Allow,
    /// Explicitly deny matching operations.
    Deny,
    /// Ask for confirmation on matching operations.
    Ask,
}

/// The type of a permission update operation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum PermissionUpdateType {
    /// Add permission rules to the existing set.
    AddRules,
    /// Replace all existing rules with the provided rules.
    ReplaceRules,
    /// Remove matching rules from the existing set.
    RemoveRules,
    /// Set the current permission mode.
    SetMode,
    /// Add directories to the permission scope.
    AddDirectories,
    /// Remove directories from the permission scope.
    RemoveDirectories,
}

/// Configuration for updating permissions programmatically.
///
/// Used to modify permission rules, change modes, or manage directory access
/// during a session.
///
/// # Fields
///
/// - `type_` — The type of permission update operation.
/// - `rules` — Rules for add/replace/remove operations.
/// - `behavior` — Behavior for rule-based operations (`"allow"`, `"deny"`, `"ask"`).
/// - `mode` — Mode for `SetMode` operations.
/// - `directories` — Directories for add/remove directory operations.
/// - `destination` — Where to apply the permission update.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PermissionUpdate {
    /// Operation type to apply.
    #[serde(rename = "type")]
    pub type_: PermissionUpdateType,
    /// Rule set used by rule-based updates.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rules: Option<Vec<PermissionRuleValue>>,
    /// Behavior used by rule-based updates.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub behavior: Option<PermissionBehavior>,
    /// Permission mode used by `SetMode`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mode: Option<PermissionMode>,
    /// Directory paths used by directory updates.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub directories: Option<Vec<String>>,
    /// Where this update should be persisted/applied.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub destination: Option<PermissionUpdateDestination>,
}

impl PermissionUpdate {
    /// Converts this permission update to a JSON value suitable for the CLI protocol.
    ///
    /// # Example
    ///
    /// ```rust
    /// use claude_code::{PermissionUpdate};
    /// use claude_code::types::{PermissionBehavior, PermissionRuleValue, PermissionUpdateType};
    ///
    /// let update = PermissionUpdate {
    ///     type_: PermissionUpdateType::AddRules,
    ///     rules: Some(vec![PermissionRuleValue {
    ///         tool_name: "Bash".to_string(),
    ///         rule_content: Some("git status".to_string()),
    ///     }]),
    ///     behavior: Some(PermissionBehavior::Allow),
    ///     mode: None,
    ///     directories: None,
    ///     destination: None,
    /// };
    ///
    /// let json = update.to_cli_dict();
    /// assert_eq!(json["type"], "addRules");
    /// ```
    pub fn to_cli_dict(&self) -> Value {
        let mut result = serde_json::Map::new();
        result.insert(
            "type".to_string(),
            serde_json::to_value(&self.type_).unwrap_or(Value::Null),
        );

        if let Some(destination) = &self.destination {
            result.insert(
                "destination".to_string(),
                serde_json::to_value(destination).unwrap_or(Value::Null),
            );
        }

        match self.type_ {
            PermissionUpdateType::AddRules
            | PermissionUpdateType::ReplaceRules
            | PermissionUpdateType::RemoveRules => {
                if let Some(rules) = &self.rules {
                    let rules_json: Vec<Value> = rules
                        .iter()
                        .map(|rule| {
                            serde_json::json!({
                                "toolName": rule.tool_name,
                                "ruleContent": rule.rule_content
                            })
                        })
                        .collect();
                    result.insert("rules".to_string(), Value::Array(rules_json));
                }
                if let Some(behavior) = &self.behavior {
                    result.insert(
                        "behavior".to_string(),
                        serde_json::to_value(behavior).unwrap_or(Value::Null),
                    );
                }
            }
            PermissionUpdateType::SetMode => {
                if let Some(mode) = &self.mode {
                    result.insert(
                        "mode".to_string(),
                        serde_json::to_value(mode).unwrap_or(Value::Null),
                    );
                }
            }
            PermissionUpdateType::AddDirectories | PermissionUpdateType::RemoveDirectories => {
                if let Some(directories) = &self.directories {
                    result.insert(
                        "directories".to_string(),
                        serde_json::to_value(directories).unwrap_or(Value::Null),
                    );
                }
            }
        }

        Value::Object(result)
    }
}

/// Context information passed to tool permission callbacks.
///
/// Provides additional context when the [`CanUseToolCallback`] is invoked, including
/// permission update suggestions from the CLI.
///
/// # Fields
///
/// - `suggestions` — Permission update suggestions from the CLI for the user to consider.
/// - `blocked_path` — Optional path rejected by permission checks.
/// - `signal` — Reserved placeholder for future abort signal support.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct ToolPermissionContext {
    /// CLI-suggested permission updates for this tool request.
    #[serde(default)]
    pub suggestions: Vec<PermissionUpdate>,
    /// Optional blocked path associated with the request.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub blocked_path: Option<String>,
    /// Reserved signal placeholder for future API compatibility.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signal: Option<()>,
}

/// Result indicating the tool call should be allowed.
///
/// Returned from a [`CanUseToolCallback`] to approve tool execution.
///
/// # Fields
///
/// - `updated_input` — Optional modified input to use instead of the original.
/// - `updated_permissions` — Optional permission updates to apply alongside this approval.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct PermissionResultAllow {
    /// Optional rewritten tool input payload.
    pub updated_input: Option<Value>,
    /// Optional additional permission updates to apply.
    pub updated_permissions: Option<Vec<PermissionUpdate>>,
}

/// Result indicating the tool call should be denied.
///
/// Returned from a [`CanUseToolCallback`] to reject tool execution.
///
/// # Fields
///
/// - `message` — Message explaining why the tool was denied.
/// - `interrupt` — Whether to interrupt the current execution entirely.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct PermissionResultDeny {
    /// Human-readable denial reason.
    pub message: String,
    /// Whether processing should be interrupted after denial.
    pub interrupt: bool,
}

/// Union type for permission callback results.
///
/// Returned by [`CanUseToolCallback`] functions to indicate whether a tool call
/// should be allowed or denied.
#[derive(Debug, Clone, PartialEq)]
pub enum PermissionResult {
    /// Approve the tool call with optional adjusted input/permissions.
    Allow(PermissionResultAllow),
    /// Reject the tool call.
    Deny(PermissionResultDeny),
}

/// Callback type for custom tool permission logic.
///
/// This function is invoked before each tool execution, receiving:
/// - `tool_name` (`String`) — The name of the tool being called.
/// - `input_data` (`Value`) — The tool's input parameters.
/// - `context` ([`ToolPermissionContext`]) — Additional context including permission suggestions.
///
/// Returns a [`PermissionResult`] indicating whether the tool call should be allowed or denied.
///
/// # Note
///
/// When using `can_use_tool`, the prompt must be provided as streaming messages
/// (not a plain text string), and `permission_prompt_tool_name` must not be set.
pub type CanUseToolCallback = Arc<
    dyn Fn(
            String,
            Value,
            ToolPermissionContext,
        ) -> BoxFuture<'static, std::result::Result<PermissionResult, Error>>
        + Send
        + Sync,
>;

/// Context information passed to hook callbacks.
///
/// Currently a marker type; reserved for future abort signal support.
#[derive(Debug, Clone, Default)]
pub struct HookContext;

/// Input data passed to hook callbacks.
///
/// A raw JSON value whose structure depends on the hook event type (e.g.,
/// `PreToolUse`, `PostToolUse`, `UserPromptSubmit`, etc.).
/// See the [hooks documentation](https://platform.claude.com/docs/en/agent-sdk/hooks)
/// for the expected shapes per event.
pub type HookInput = Value;

/// Return value from hook callbacks.
///
/// A JSON value that may contain control fields such as:
/// - `decision` — `"block"` to block the action.
/// - `systemMessage` — A system message to add to the transcript.
/// - `hookSpecificOutput` — Hook-specific output data.
/// - `continue_` — Whether to proceed (maps to `"continue"` in the CLI protocol).
/// - `async_` — Set to `true` to defer execution (maps to `"async"` in the CLI protocol).
pub type HookJSONOutput = Value;

/// Callback type for hook functions.
///
/// Invoked when a matching hook event occurs. Receives:
/// - `input` ([`HookInput`]) — Event-specific input data.
/// - `tool_use_id` (`Option<String>`) — Optional tool use identifier (for tool-related hooks).
/// - `context` ([`HookContext`]) — Hook context with additional information.
///
/// Returns a [`HookJSONOutput`] JSON value with optional control and output fields.
pub type HookCallback = Arc<
    dyn Fn(
            HookInput,
            Option<String>,
            HookContext,
        ) -> BoxFuture<'static, std::result::Result<HookJSONOutput, Error>>
        + Send
        + Sync,
>;

/// Configuration for matching hooks to specific events or tools.
///
/// # Fields
///
/// - `matcher` — Optional tool name or regex pattern to match (e.g., `"Bash"`, `"Write|Edit"`).
///   If `None`, the hook applies to all tools.
/// - `hooks` — List of callback functions to execute when matched.
/// - `timeout` — Optional timeout in seconds for all hooks in this matcher (default: 60).
#[derive(Clone, Default)]
pub struct HookMatcher {
    /// Optional matcher expression for selecting hook targets.
    pub matcher: Option<String>,
    /// Hook callbacks to execute when this matcher is selected.
    pub hooks: Vec<HookCallback>,
    /// Optional timeout in seconds applied to callbacks in this matcher.
    pub timeout: Option<f64>,
}

/// Configuration for an MCP server using stdio transport.
///
/// Launches an external process and communicates via stdin/stdout.
///
/// # Fields
///
/// - `type_` — Optional; set to `"stdio"` for explicit typing (backwards compatible if omitted).
/// - `command` — The command to execute.
/// - `args` — Optional command-line arguments.
/// - `env` — Optional environment variables to set.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct McpStdioServerConfig {
    /// Optional discriminator for stdio transport (`"stdio"`).
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub type_: Option<String>,
    /// Command used to launch the MCP server process.
    pub command: String,
    /// Optional command arguments.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub args: Option<Vec<String>>,
    /// Optional environment variables passed to the process.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub env: Option<HashMap<String, String>>,
}

/// Configuration for an MCP server using Server-Sent Events (SSE) transport.
///
/// # Fields
///
/// - `type_` — Must be `"sse"`.
/// - `url` — The SSE endpoint URL.
/// - `headers` — Optional HTTP headers to include in requests.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct McpSSEServerConfig {
    /// Discriminator for SSE transport (`"sse"`).
    #[serde(rename = "type")]
    pub type_: String,
    /// SSE endpoint URL.
    pub url: String,
    /// Optional HTTP headers for the SSE connection.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<HashMap<String, String>>,
}

/// Configuration for an MCP server using HTTP transport.
///
/// # Fields
///
/// - `type_` — Must be `"http"`.
/// - `url` — The HTTP endpoint URL.
/// - `headers` — Optional HTTP headers to include in requests.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct McpHttpServerConfig {
    /// Discriminator for HTTP transport (`"http"`).
    #[serde(rename = "type")]
    pub type_: String,
    /// HTTP endpoint URL.
    pub url: String,
    /// Optional HTTP headers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<HashMap<String, String>>,
}

/// Configuration for an in-process SDK MCP server.
///
/// Created via [`create_sdk_mcp_server()`](crate::create_sdk_mcp_server). The server
/// runs within your Rust application and handles tool calls in-process.
///
/// # Fields
///
/// - `type_` — Always `"sdk"`.
/// - `name` — Unique name identifier for the server.
/// - `instance` — Shared reference to the [`McpSdkServer`] instance.
#[derive(Clone)]
pub struct McpSdkServerConfig {
    /// Discriminator for in-process SDK transport (`"sdk"`).
    pub type_: String,
    /// Logical server name used in MCP config maps.
    pub name: String,
    /// In-process server instance.
    pub instance: Arc<McpSdkServer>,
}

/// Union type for MCP server configurations.
///
/// Supports four transport types for MCP (Model Context Protocol) servers:
///
/// - `Stdio` — External process communicating via stdin/stdout.
/// - `Sse` — Remote server using Server-Sent Events.
/// - `Http` — Remote server using HTTP.
/// - `Sdk` — In-process server running within your application.
#[derive(Clone)]
pub enum McpServerConfig {
    /// External stdio MCP server process.
    Stdio(McpStdioServerConfig),
    /// Remote SSE MCP server.
    Sse(McpSSEServerConfig),
    /// Remote HTTP MCP server.
    Http(McpHttpServerConfig),
    /// In-process SDK MCP server.
    Sdk(McpSdkServerConfig),
}

impl McpServerConfig {
    /// Converts this configuration to a JSON value for the CLI protocol.
    ///
    /// SDK-type servers are serialized as `{"type": "sdk", "name": "<name>"}` since
    /// the actual server instance runs in-process and doesn't need full serialization.
    ///
    /// # Example
    ///
    /// ```rust
    /// use claude_code::{McpServerConfig, McpSSEServerConfig};
    ///
    /// let config = McpServerConfig::Sse(McpSSEServerConfig {
    ///     type_: "sse".to_string(),
    ///     url: "https://example.com/mcp".to_string(),
    ///     headers: None,
    /// });
    ///
    /// let json = config.to_cli_json();
    /// assert_eq!(json["type"], "sse");
    /// ```
    pub fn to_cli_json(&self) -> Value {
        match self {
            McpServerConfig::Stdio(config) => serde_json::to_value(config).unwrap_or(Value::Null),
            McpServerConfig::Sse(config) => serde_json::to_value(config).unwrap_or(Value::Null),
            McpServerConfig::Http(config) => serde_json::to_value(config).unwrap_or(Value::Null),
            McpServerConfig::Sdk(config) => {
                serde_json::json!({
                    "type": "sdk",
                    "name": config.name
                })
            }
        }
    }
}

/// MCP server configuration option for [`ClaudeAgentOptions`].
///
/// # Variants
///
/// - `None` — No MCP servers configured (default).
/// - `Servers` — A map of server name to [`McpServerConfig`].
/// - `Raw` — A raw JSON string or file path to an MCP configuration.
#[derive(Clone, Default)]
pub enum McpServersOption {
    #[default]
    /// No MCP servers are configured.
    None,
    /// Explicit map of server names to server configs.
    Servers(HashMap<String, McpServerConfig>),
    /// Raw CLI `--mcp-config` payload (JSON string or path).
    Raw(String),
}

/// SDK MCP server config shape used in MCP status responses.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct McpSdkServerStatusConfig {
    /// Discriminator for in-process SDK transport (`"sdk"`).
    #[serde(rename = "type")]
    pub type_: String,
    /// Logical server name used in MCP config maps.
    pub name: String,
}

/// Claude.ai proxy MCP server config shape used in MCP status responses.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct McpClaudeAiProxyServerConfig {
    /// Discriminator for Claude.ai proxy transport (`"claudeai-proxy"`).
    #[serde(rename = "type")]
    pub type_: String,
    /// Proxy endpoint URL.
    pub url: String,
    /// Proxy identifier.
    pub id: String,
}

/// MCP server config shape returned by `get_mcp_status`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum McpServerStatusConfig {
    /// stdio server configuration.
    Stdio(McpStdioServerConfig),
    /// SSE server configuration.
    Sse(McpSSEServerConfig),
    /// HTTP server configuration.
    Http(McpHttpServerConfig),
    /// In-process SDK server configuration.
    Sdk(McpSdkServerStatusConfig),
    /// Claude.ai proxy server configuration.
    ClaudeAiProxy(McpClaudeAiProxyServerConfig),
    /// Forward-compatible fallback for unknown config payloads.
    Unknown(Value),
}

impl Serialize for McpServerStatusConfig {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            McpServerStatusConfig::Stdio(value) => value.serialize(serializer),
            McpServerStatusConfig::Sse(value) => value.serialize(serializer),
            McpServerStatusConfig::Http(value) => value.serialize(serializer),
            McpServerStatusConfig::Sdk(value) => value.serialize(serializer),
            McpServerStatusConfig::ClaudeAiProxy(value) => value.serialize(serializer),
            McpServerStatusConfig::Unknown(value) => value.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for McpServerStatusConfig {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = Value::deserialize(deserializer)?;
        let config_type = value
            .get("type")
            .and_then(Value::as_str)
            .unwrap_or_default();

        match config_type {
            "stdio" => serde_json::from_value::<McpStdioServerConfig>(value)
                .map(McpServerStatusConfig::Stdio)
                .map_err(serde::de::Error::custom),
            "sse" => serde_json::from_value::<McpSSEServerConfig>(value)
                .map(McpServerStatusConfig::Sse)
                .map_err(serde::de::Error::custom),
            "http" => serde_json::from_value::<McpHttpServerConfig>(value)
                .map(McpServerStatusConfig::Http)
                .map_err(serde::de::Error::custom),
            "sdk" => serde_json::from_value::<McpSdkServerStatusConfig>(value)
                .map(McpServerStatusConfig::Sdk)
                .map_err(serde::de::Error::custom),
            "claudeai-proxy" => serde_json::from_value::<McpClaudeAiProxyServerConfig>(value)
                .map(McpServerStatusConfig::ClaudeAiProxy)
                .map_err(serde::de::Error::custom),
            _ => Ok(McpServerStatusConfig::Unknown(value)),
        }
    }
}

/// Tool annotations returned in MCP status payloads.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct McpToolAnnotations {
    /// Whether the tool is read-only.
    #[serde(rename = "readOnly", skip_serializing_if = "Option::is_none")]
    pub read_only: Option<bool>,
    /// Whether the tool is destructive.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub destructive: Option<bool>,
    /// Whether the tool interacts with open-world/external systems.
    #[serde(rename = "openWorld", skip_serializing_if = "Option::is_none")]
    pub open_world: Option<bool>,
}

/// Tool metadata returned in MCP status payloads.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct McpToolInfo {
    /// Tool name.
    pub name: String,
    /// Optional tool description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Optional tool annotations.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<McpToolAnnotations>,
}

/// Server metadata returned for connected MCP servers.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct McpServerInfo {
    /// Server name.
    pub name: String,
    /// Server version.
    pub version: String,
}

/// MCP server connection status.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum McpServerConnectionStatus {
    /// Server is connected.
    #[serde(rename = "connected")]
    Connected,
    /// Server connection failed.
    #[serde(rename = "failed")]
    Failed,
    /// Server needs authentication.
    #[serde(rename = "needs-auth")]
    NeedsAuth,
    /// Server connection is pending.
    #[serde(rename = "pending")]
    Pending,
    /// Server is disabled.
    #[serde(rename = "disabled")]
    Disabled,
}

/// Status entry for a single MCP server.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct McpServerStatus {
    /// Server name as configured.
    pub name: String,
    /// Current connection status.
    pub status: McpServerConnectionStatus,
    /// Server info from MCP initialize handshake.
    #[serde(rename = "serverInfo", skip_serializing_if = "Option::is_none")]
    pub server_info: Option<McpServerInfo>,
    /// Error message when status is `failed`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Server configuration payload.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub config: Option<McpServerStatusConfig>,
    /// Configuration scope (for example `project`, `user`, `local`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope: Option<String>,
    /// Tools exposed by this server.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<McpToolInfo>>,
}

/// Typed MCP status response payload returned by `get_mcp_status`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct McpStatusResponse {
    /// Status entries for all configured servers.
    #[serde(rename = "mcpServers")]
    pub mcp_servers: Vec<McpServerStatus>,
}

/// Configuration for loading plugins in the SDK.
///
/// Only local plugins are currently supported.
///
/// # Fields
///
/// - `type_` — Must be `"local"`.
/// - `path` — Absolute or relative path to the plugin directory.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SdkPluginConfig {
    /// Plugin type discriminator (currently `"local"`).
    #[serde(rename = "type")]
    pub type_: String,
    /// Filesystem path to the plugin directory.
    pub path: String,
}

/// Network-specific configuration for sandbox mode.
///
/// Controls how sandboxed processes can access network resources.
///
/// # Fields
///
/// - `allow_unix_sockets` — Unix socket paths that processes can access (e.g., Docker socket).
/// - `allow_all_unix_sockets` — Allow access to all Unix sockets.
/// - `allow_local_binding` — Allow processes to bind to local ports (e.g., for dev servers).
/// - `http_proxy_port` — HTTP proxy port for network requests.
/// - `socks_proxy_port` — SOCKS proxy port for network requests.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct SandboxNetworkConfig {
    /// Allowed unix socket paths.
    #[serde(rename = "allowUnixSockets", skip_serializing_if = "Option::is_none")]
    pub allow_unix_sockets: Option<Vec<String>>,
    /// Whether all unix sockets are allowed.
    #[serde(
        rename = "allowAllUnixSockets",
        skip_serializing_if = "Option::is_none"
    )]
    pub allow_all_unix_sockets: Option<bool>,
    /// Whether local port binding is allowed.
    #[serde(rename = "allowLocalBinding", skip_serializing_if = "Option::is_none")]
    pub allow_local_binding: Option<bool>,
    /// HTTP proxy port exposed into the sandbox.
    #[serde(rename = "httpProxyPort", skip_serializing_if = "Option::is_none")]
    pub http_proxy_port: Option<u16>,
    /// SOCKS proxy port exposed into the sandbox.
    #[serde(rename = "socksProxyPort", skip_serializing_if = "Option::is_none")]
    pub socks_proxy_port: Option<u16>,
}

/// Configuration for ignoring specific sandbox violations.
///
/// # Fields
///
/// - `file` — File path patterns to ignore violations for.
/// - `network` — Network patterns to ignore violations for.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct SandboxIgnoreViolations {
    /// File path patterns to ignore.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file: Option<Vec<String>>,
    /// Network patterns to ignore.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub network: Option<Vec<String>>,
}

/// Sandbox configuration for controlling command execution isolation.
///
/// Use this to enable command sandboxing and configure network restrictions
/// programmatically.
///
/// # Fields
///
/// - `enabled` — Enable sandbox mode for command execution.
/// - `auto_allow_bash_if_sandboxed` — Auto-approve bash commands when sandbox is enabled.
/// - `excluded_commands` — Commands that always bypass sandbox restrictions (e.g., `["docker"]`).
/// - `allow_unsandboxed_commands` — Allow the model to request running commands outside the sandbox.
/// - `network` — Network-specific sandbox configuration.
/// - `ignore_violations` — Configure which sandbox violations to ignore.
/// - `enable_weaker_nested_sandbox` — Enable a weaker nested sandbox for compatibility.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct SandboxSettings {
    /// Enables or disables sandboxing.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    /// Auto-approve bash tool when sandboxing is enabled.
    #[serde(
        rename = "autoAllowBashIfSandboxed",
        skip_serializing_if = "Option::is_none"
    )]
    pub auto_allow_bash_if_sandboxed: Option<bool>,
    /// Commands excluded from sandbox restrictions.
    #[serde(rename = "excludedCommands", skip_serializing_if = "Option::is_none")]
    pub excluded_commands: Option<Vec<String>>,
    /// Whether unsandboxed command execution can be requested.
    #[serde(
        rename = "allowUnsandboxedCommands",
        skip_serializing_if = "Option::is_none"
    )]
    pub allow_unsandboxed_commands: Option<bool>,
    /// Network-related sandbox settings.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub network: Option<SandboxNetworkConfig>,
    /// Violation categories to ignore.
    #[serde(rename = "ignoreViolations", skip_serializing_if = "Option::is_none")]
    pub ignore_violations: Option<SandboxIgnoreViolations>,
    /// Enables weaker nested sandbox mode for compatibility.
    #[serde(
        rename = "enableWeakerNestedSandbox",
        skip_serializing_if = "Option::is_none"
    )]
    pub enable_weaker_nested_sandbox: Option<bool>,
}

/// A text content block in an assistant message.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TextBlock {
    /// Textual content for this block.
    pub text: String,
}

/// A thinking content block (for models with extended thinking capability).
///
/// Contains the model's internal reasoning and a cryptographic signature.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ThinkingBlock {
    /// Model-generated reasoning content.
    pub thinking: String,
    /// Signature associated with the reasoning block.
    pub signature: String,
}

/// A tool use request block.
///
/// Represents Claude's request to invoke a specific tool with given parameters.
///
/// # Fields
///
/// - `id` — Unique identifier for this tool use request.
/// - `name` — Name of the tool to invoke.
/// - `input` — JSON input parameters for the tool.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ToolUseBlock {
    /// Tool use identifier.
    pub id: String,
    /// Invoked tool name.
    pub name: String,
    /// Tool input payload.
    pub input: Value,
}

/// A tool execution result block.
///
/// Contains the output from a previously executed tool.
///
/// # Fields
///
/// - `tool_use_id` — The ID of the [`ToolUseBlock`] this result corresponds to.
/// - `content` — Optional result content (text or structured data).
/// - `is_error` — Whether the tool execution resulted in an error.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ToolResultBlock {
    /// Corresponding tool use identifier.
    pub tool_use_id: String,
    /// Optional tool result payload.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<Value>,
    /// Whether this tool result represents an error.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_error: Option<bool>,
}

/// Union type for all content block types in messages.
///
/// Content blocks make up the body of [`AssistantMessage`] and [`UserMessage`] responses.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ContentBlock {
    /// Plain text content.
    Text(TextBlock),
    /// Reasoning content.
    Thinking(ThinkingBlock),
    /// Tool invocation request.
    ToolUse(ToolUseBlock),
    /// Tool invocation result.
    ToolResult(ToolResultBlock),
}

/// User message content — either plain text or structured content blocks.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum UserContent {
    /// Plain string user content.
    Text(String),
    /// Structured content blocks.
    Blocks(Vec<ContentBlock>),
}

/// A user input message.
///
/// # Fields
///
/// - `content` — Message content as text or content blocks.
/// - `uuid` — Optional unique message identifier.
/// - `parent_tool_use_id` — Tool use ID if this message is a tool result response.
/// - `tool_use_result` — Tool result data if applicable.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct UserMessage {
    /// User message body.
    pub content: UserContent,
    /// Optional message UUID.
    pub uuid: Option<String>,
    /// Optional parent tool use identifier.
    pub parent_tool_use_id: Option<String>,
    /// Optional embedded tool-use result payload.
    pub tool_use_result: Option<Value>,
}

/// An assistant response message with content blocks.
///
/// # Fields
///
/// - `content` — List of content blocks in the response.
/// - `model` — The model that generated this response.
/// - `parent_tool_use_id` — Tool use ID if this is a nested subagent response.
/// - `error` — Error type string if the response encountered an error
///   (e.g., `"authentication_failed"`, `"rate_limit"`, `"server_error"`).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AssistantMessage {
    /// Assistant content blocks.
    pub content: Vec<ContentBlock>,
    /// Model identifier used for generation.
    pub model: String,
    /// Optional parent tool use identifier.
    pub parent_tool_use_id: Option<String>,
    /// Optional error classification string.
    pub error: Option<String>,
}

/// A system message with metadata.
///
/// # Fields
///
/// - `subtype` — The system message subtype identifier.
/// - `data` — The full raw data of the system message.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SystemMessage {
    /// System message subtype.
    pub subtype: String,
    /// Full raw system payload.
    pub data: Value,
}

/// Token/tool usage reported in task-related system messages.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TaskUsage {
    /// Total token count used so far.
    pub total_tokens: i64,
    /// Number of tool invocations used so far.
    pub tool_uses: i64,
    /// Task duration in milliseconds.
    pub duration_ms: i64,
}

/// Status values for task notification messages.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum TaskNotificationStatus {
    /// Task completed successfully.
    #[serde(rename = "completed")]
    Completed,
    /// Task failed.
    #[serde(rename = "failed")]
    Failed,
    /// Task was stopped.
    #[serde(rename = "stopped")]
    Stopped,
}

/// Typed view for `system` messages with subtype `task_started`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TaskStartedMessage {
    /// Always `task_started`.
    pub subtype: String,
    /// Raw system payload.
    pub data: Value,
    /// Task identifier.
    pub task_id: String,
    /// Human-readable task description.
    pub description: String,
    /// Message UUID.
    pub uuid: String,
    /// Session identifier.
    pub session_id: String,
    /// Optional parent tool use id.
    pub tool_use_id: Option<String>,
    /// Optional task type.
    pub task_type: Option<String>,
}

/// Typed view for `system` messages with subtype `task_progress`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TaskProgressMessage {
    /// Always `task_progress`.
    pub subtype: String,
    /// Raw system payload.
    pub data: Value,
    /// Task identifier.
    pub task_id: String,
    /// Human-readable task description.
    pub description: String,
    /// Current task usage metrics.
    pub usage: TaskUsage,
    /// Message UUID.
    pub uuid: String,
    /// Session identifier.
    pub session_id: String,
    /// Optional parent tool use id.
    pub tool_use_id: Option<String>,
    /// Optional last tool name.
    pub last_tool_name: Option<String>,
}

/// Typed view for `system` messages with subtype `task_notification`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TaskNotificationMessage {
    /// Always `task_notification`.
    pub subtype: String,
    /// Raw system payload.
    pub data: Value,
    /// Task identifier.
    pub task_id: String,
    /// Task status.
    pub status: TaskNotificationStatus,
    /// Output file path.
    pub output_file: String,
    /// Human-readable task summary.
    pub summary: String,
    /// Message UUID.
    pub uuid: String,
    /// Session identifier.
    pub session_id: String,
    /// Optional parent tool use id.
    pub tool_use_id: Option<String>,
    /// Optional task usage metrics.
    pub usage: Option<TaskUsage>,
}

impl SystemMessage {
    /// Returns a typed `TaskStartedMessage` view for `task_started` messages.
    pub fn as_task_started(&self) -> Option<TaskStartedMessage> {
        if self.subtype != "task_started" {
            return None;
        }
        let obj = self.data.as_object()?;
        Some(TaskStartedMessage {
            subtype: self.subtype.clone(),
            data: self.data.clone(),
            task_id: obj.get("task_id")?.as_str()?.to_string(),
            description: obj.get("description")?.as_str()?.to_string(),
            uuid: obj.get("uuid")?.as_str()?.to_string(),
            session_id: obj.get("session_id")?.as_str()?.to_string(),
            tool_use_id: obj
                .get("tool_use_id")
                .and_then(Value::as_str)
                .map(ToString::to_string),
            task_type: obj
                .get("task_type")
                .and_then(Value::as_str)
                .map(ToString::to_string),
        })
    }

    /// Returns a typed `TaskProgressMessage` view for `task_progress` messages.
    pub fn as_task_progress(&self) -> Option<TaskProgressMessage> {
        if self.subtype != "task_progress" {
            return None;
        }
        let obj = self.data.as_object()?;
        let usage = serde_json::from_value::<TaskUsage>(obj.get("usage")?.clone()).ok()?;
        Some(TaskProgressMessage {
            subtype: self.subtype.clone(),
            data: self.data.clone(),
            task_id: obj.get("task_id")?.as_str()?.to_string(),
            description: obj.get("description")?.as_str()?.to_string(),
            usage,
            uuid: obj.get("uuid")?.as_str()?.to_string(),
            session_id: obj.get("session_id")?.as_str()?.to_string(),
            tool_use_id: obj
                .get("tool_use_id")
                .and_then(Value::as_str)
                .map(ToString::to_string),
            last_tool_name: obj
                .get("last_tool_name")
                .and_then(Value::as_str)
                .map(ToString::to_string),
        })
    }

    /// Returns a typed `TaskNotificationMessage` view for `task_notification` messages.
    pub fn as_task_notification(&self) -> Option<TaskNotificationMessage> {
        if self.subtype != "task_notification" {
            return None;
        }
        let obj = self.data.as_object()?;
        let status =
            serde_json::from_value::<TaskNotificationStatus>(obj.get("status")?.clone()).ok()?;
        let usage = obj
            .get("usage")
            .and_then(|value| serde_json::from_value::<TaskUsage>(value.clone()).ok());
        Some(TaskNotificationMessage {
            subtype: self.subtype.clone(),
            data: self.data.clone(),
            task_id: obj.get("task_id")?.as_str()?.to_string(),
            status,
            output_file: obj.get("output_file")?.as_str()?.to_string(),
            summary: obj.get("summary")?.as_str()?.to_string(),
            uuid: obj.get("uuid")?.as_str()?.to_string(),
            session_id: obj.get("session_id")?.as_str()?.to_string(),
            tool_use_id: obj
                .get("tool_use_id")
                .and_then(Value::as_str)
                .map(ToString::to_string),
            usage,
        })
    }
}

/// Final result message with cost and usage information.
///
/// This is the last message received for a query, containing summary statistics.
///
/// # Fields
///
/// - `subtype` — The result subtype (e.g., `"success"`, `"error"`).
/// - `duration_ms` — Total wall-clock duration in milliseconds.
/// - `duration_api_ms` — Time spent in API calls in milliseconds.
/// - `is_error` — Whether the query resulted in an error.
/// - `num_turns` — Number of conversation turns in the query.
/// - `session_id` — The session identifier.
/// - `stop_reason` — Optional reason for why the turn ended.
/// - `total_cost_usd` — Optional total cost in USD.
/// - `usage` — Optional token usage breakdown (input_tokens, output_tokens,
///   cache_creation_input_tokens, cache_read_input_tokens).
/// - `result` — Optional result text.
/// - `structured_output` — Optional structured output if `output_format` was configured.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ResultMessage {
    /// Result subtype.
    pub subtype: String,
    /// End-to-end duration in milliseconds.
    pub duration_ms: i64,
    /// API-only duration in milliseconds.
    pub duration_api_ms: i64,
    /// Indicates whether execution ended in error.
    pub is_error: bool,
    /// Number of turns performed.
    pub num_turns: i64,
    /// Session identifier.
    pub session_id: String,
    /// Optional reason for why the turn ended.
    pub stop_reason: Option<String>,
    /// Optional total cost in USD.
    pub total_cost_usd: Option<f64>,
    /// Optional usage summary payload.
    pub usage: Option<Value>,
    /// Optional text result.
    pub result: Option<String>,
    /// Optional structured output payload.
    pub structured_output: Option<Value>,
}

/// Stream event for partial message updates during streaming.
///
/// Only received when `include_partial_messages` is set to `true` in [`ClaudeAgentOptions`].
///
/// # Fields
///
/// - `uuid` — Unique identifier for this event.
/// - `session_id` — Session identifier.
/// - `event` — The raw Claude API stream event data.
/// - `parent_tool_use_id` — Parent tool use ID if this event is from a subagent.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StreamEvent {
    /// Event identifier.
    pub uuid: String,
    /// Session identifier for this event.
    pub session_id: String,
    /// Raw stream event payload.
    pub event: Value,
    /// Optional parent tool use identifier.
    pub parent_tool_use_id: Option<String>,
}

/// Session metadata returned by [`list_sessions`](crate::list_sessions).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SDKSessionInfo {
    /// Session identifier (UUID).
    pub session_id: String,
    /// Display summary for the session.
    pub summary: String,
    /// Last modified time in milliseconds since epoch.
    pub last_modified: i64,
    /// Session file size in bytes.
    pub file_size: u64,
    /// User-defined custom title if present.
    pub custom_title: Option<String>,
    /// First meaningful prompt from the session.
    pub first_prompt: Option<String>,
    /// Git branch associated with the session.
    pub git_branch: Option<String>,
    /// Working directory associated with the session.
    pub cwd: Option<String>,
}

/// User/assistant message returned by [`get_session_messages`](crate::get_session_messages).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SessionMessage {
    /// Message type (`"user"` or `"assistant"`).
    #[serde(rename = "type")]
    pub type_: String,
    /// Message UUID.
    pub uuid: String,
    /// Session identifier.
    pub session_id: String,
    /// Raw Anthropic message payload.
    pub message: Value,
    /// Always `None` for top-level conversation messages.
    pub parent_tool_use_id: Option<String>,
}

/// Union type of all possible messages from the Claude Code CLI.
///
/// When receiving messages via [`ClaudeSdkClient::receive_message()`](crate::ClaudeSdkClient::receive_message)
/// or iterating results from [`query()`](crate::query_fn::query), each message will be one of these variants.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum Message {
    /// A user input message echoed back.
    User(UserMessage),
    /// An assistant response with content blocks.
    Assistant(AssistantMessage),
    /// A system notification or status message.
    System(SystemMessage),
    /// The final result message with cost/usage information.
    Result(ResultMessage),
    /// A partial streaming event (only when `include_partial_messages` is enabled).
    StreamEvent(StreamEvent),
}

/// Controls extended thinking behavior.
///
/// Extended thinking allows Claude to reason through complex problems before responding.
///
/// # Variants
///
/// - `Adaptive` — Claude adaptively decides when and how much to think.
/// - `Enabled { budget_tokens }` — Enable thinking with a specific token budget.
/// - `Disabled` — Disable extended thinking entirely.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type")]
pub enum ThinkingConfig {
    /// Let Claude pick thinking depth adaptively.
    #[serde(rename = "adaptive")]
    Adaptive,
    /// Enable explicit thinking with a fixed token budget.
    #[serde(rename = "enabled")]
    Enabled {
        /// Maximum reasoning token budget when thinking is enabled.
        budget_tokens: i64,
    },
    /// Disable thinking blocks.
    #[serde(rename = "disabled")]
    Disabled,
}

/// MCP tool annotations providing hints about tool behavior.
///
/// These annotations help Claude and the system understand tool characteristics
/// for better permission handling and execution planning.
///
/// # Fields
///
/// - `read_only_hint` — Whether the tool only reads data without side effects.
/// - `destructive_hint` — Whether the tool performs destructive operations.
/// - `idempotent_hint` — Whether calling the tool multiple times has the same effect as once.
/// - `open_world_hint` — Whether the tool interacts with external systems.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "camelCase")]
pub struct ToolAnnotations {
    /// Hint that the tool is read-only.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub read_only_hint: Option<bool>,
    /// Hint that the tool may be destructive.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub destructive_hint: Option<bool>,
    /// Hint that repeated calls have same effect.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub idempotent_hint: Option<bool>,
    /// Hint that the tool interacts with external/open systems.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub open_world_hint: Option<bool>,
}

/// Main configuration for Claude Code queries and sessions.
///
/// This is the primary configuration struct passed to [`query()`](crate::query_fn::query) or
/// [`ClaudeSdkClient::new()`](crate::ClaudeSdkClient::new). All fields are optional
/// and have sensible defaults.
///
/// Corresponds to the Python SDK's `ClaudeAgentOptions` dataclass.
///
/// # Fields
///
/// | Field | Description |
/// |-------|-------------|
/// | `tools` | Tools configuration — explicit list or preset |
/// | `allowed_tools` | List of allowed tool names |
/// | `system_prompt` | System prompt — custom text or preset |
/// | `mcp_servers` | MCP server configurations |
/// | `permission_mode` | Permission mode for tool usage |
/// | `continue_conversation` | Continue the most recent conversation |
/// | `resume` | Session ID to resume |
/// | `max_turns` | Maximum conversation turns |
/// | `max_budget_usd` | Maximum budget in USD for the session |
/// | `disallowed_tools` | List of disallowed tool names |
/// | `model` | Claude model to use |
/// | `fallback_model` | Fallback model if the primary fails |
/// | `betas` | Beta features to enable |
/// | `permission_prompt_tool_name` | MCP tool name for permission prompts |
/// | `cwd` | Current working directory |
/// | `cli_path` | Custom path to the Claude Code CLI executable |
/// | `settings` | Path to settings file or inline JSON |
/// | `add_dirs` | Additional directories Claude can access |
/// | `env` | Environment variables |
/// | `extra_args` | Additional CLI arguments |
/// | `max_buffer_size` | Maximum bytes when buffering CLI stdout |
/// | `can_use_tool` | Tool permission callback function |
/// | `hooks` | Hook configurations for intercepting events |
/// | `user` | User identifier |
/// | `include_partial_messages` | Include [`StreamEvent`] partial messages |
/// | `fork_session` | Fork to new session ID when resuming |
/// | `agents` | Programmatically defined subagents |
/// | `setting_sources` | Which filesystem settings to load |
/// | `sandbox` | Sandbox configuration |
/// | `strict_settings_merge` | Fail instead of warn when sandbox/settings JSON merge fails |
/// | `plugins` | Local plugins to load |
/// | `max_thinking_tokens` | *Deprecated:* use `thinking` instead |
/// | `thinking` | Extended thinking configuration |
/// | `effort` | Effort level (`"low"`, `"medium"`, `"high"`, `"max"`) |
/// | `output_format` | Structured output format (e.g., JSON schema) |
/// | `enable_file_checkpointing` | Enable file change tracking for rewinding |
#[derive(Clone)]
pub struct ClaudeAgentOptions {
    /// Tools configuration. Use [`ToolsOption::Preset`] with [`ToolsPreset::default()`]
    /// for Claude Code's default tools.
    pub tools: Option<ToolsOption>,
    /// List of allowed tool names.
    pub allowed_tools: Vec<String>,
    /// System prompt configuration. Pass a string via [`SystemPrompt::Text`] for a custom
    /// prompt, or use [`SystemPrompt::Preset`] for Claude Code's built-in system prompt.
    pub system_prompt: Option<SystemPrompt>,
    /// MCP server configurations or path to config file.
    pub mcp_servers: McpServersOption,
    /// Permission mode for tool usage.
    pub permission_mode: Option<PermissionMode>,
    /// Continue the most recent conversation.
    pub continue_conversation: bool,
    /// Session ID to resume.
    pub resume: Option<String>,
    /// Maximum conversation turns.
    pub max_turns: Option<i64>,
    /// Maximum budget in USD for the session.
    pub max_budget_usd: Option<f64>,
    /// List of disallowed tool names.
    pub disallowed_tools: Vec<String>,
    /// Claude model to use (e.g., `"sonnet"`, `"opus"`).
    pub model: Option<String>,
    /// Fallback model to use if the primary model fails.
    pub fallback_model: Option<String>,
    /// Beta features to enable.
    pub betas: Vec<String>,
    /// MCP tool name for permission prompts. Mutually exclusive with `can_use_tool`.
    pub permission_prompt_tool_name: Option<String>,
    /// Current working directory for the Claude Code process.
    pub cwd: Option<PathBuf>,
    /// Custom path to the Claude Code CLI executable.
    pub cli_path: Option<PathBuf>,
    /// Path to settings file or inline JSON string.
    pub settings: Option<String>,
    /// Additional directories Claude can access.
    pub add_dirs: Vec<PathBuf>,
    /// Environment variables to pass to the CLI process.
    pub env: HashMap<String, String>,
    /// Additional CLI arguments to pass directly to the CLI.
    /// Keys are flag names (without `--`), values are optional flag values.
    pub extra_args: HashMap<String, Option<String>>,
    /// Maximum bytes when buffering CLI stdout. Defaults to 1MB.
    pub max_buffer_size: Option<usize>,
    /// Custom tool permission callback function.
    pub can_use_tool: Option<CanUseToolCallback>,
    /// Hook configurations for intercepting events. Keys are hook event names
    /// (e.g., `"PreToolUse"`, `"PostToolUse"`, `"UserPromptSubmit"`).
    pub hooks: Option<HashMap<String, Vec<HookMatcher>>>,
    /// User identifier.
    pub user: Option<String>,
    /// Include partial message streaming events ([`StreamEvent`]).
    pub include_partial_messages: bool,
    /// When resuming with `resume`, fork to a new session ID instead of continuing
    /// the original session.
    pub fork_session: bool,
    /// Programmatically defined subagents.
    pub agents: Option<HashMap<String, AgentDefinition>>,
    /// Control which filesystem settings to load.
    /// When omitted, no settings are loaded (SDK isolation).
    pub setting_sources: Option<Vec<SettingSource>>,
    /// Sandbox configuration for command execution isolation.
    pub sandbox: Option<SandboxSettings>,
    /// When `true`, fail command construction if sandbox merge with `settings` fails.
    /// When `false`, merge failures emit a warning and fallback to sandbox-only settings.
    pub strict_settings_merge: bool,
    /// Local plugins to load.
    pub plugins: Vec<SdkPluginConfig>,
    /// *Deprecated:* Maximum tokens for thinking blocks. Use `thinking` instead.
    pub max_thinking_tokens: Option<i64>,
    /// Extended thinking configuration. Takes precedence over `max_thinking_tokens`.
    pub thinking: Option<ThinkingConfig>,
    /// Effort level for thinking depth (`"low"`, `"medium"`, `"high"`, `"max"`).
    pub effort: Option<String>,
    /// Output format for structured responses.
    /// Example: `{"type": "json_schema", "schema": {...}}`
    pub output_format: Option<Value>,
    /// Enable file change tracking for rewinding via
    /// [`ClaudeSdkClient::rewind_files()`](crate::ClaudeSdkClient::rewind_files).
    pub enable_file_checkpointing: bool,
    /// Optional callback for stderr output lines from the CLI process.
    ///
    /// When set, stderr is piped and each non-empty line is passed to this callback.
    /// When `None`, stderr is still drained to prevent subprocess blocking, but
    /// lines are discarded.
    pub stderr: Option<StderrCallback>,
}

/// Callback type for receiving stderr output lines from the CLI process.
pub type StderrCallback = Arc<dyn Fn(String) + Send + Sync>;

impl Default for ClaudeAgentOptions {
    fn default() -> Self {
        Self {
            tools: None,
            allowed_tools: Vec::new(),
            system_prompt: None,
            mcp_servers: McpServersOption::None,
            permission_mode: None,
            continue_conversation: false,
            resume: None,
            max_turns: None,
            max_budget_usd: None,
            disallowed_tools: Vec::new(),
            model: None,
            fallback_model: None,
            betas: Vec::new(),
            permission_prompt_tool_name: None,
            cwd: None,
            cli_path: None,
            settings: None,
            add_dirs: Vec::new(),
            env: HashMap::new(),
            extra_args: HashMap::new(),
            max_buffer_size: None,
            can_use_tool: None,
            hooks: None,
            user: None,
            include_partial_messages: false,
            fork_session: false,
            agents: None,
            setting_sources: None,
            sandbox: None,
            strict_settings_merge: false,
            plugins: Vec::new(),
            max_thinking_tokens: None,
            thinking: None,
            effort: None,
            output_format: None,
            enable_file_checkpointing: false,
            stderr: None,
        }
    }
}