ironclaw 0.24.0

Secure personal AI assistant that protects your data and expands its capabilities on the fly
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
//! JSON schema for WASM tool capabilities files.
//!
//! External WASM tools declare their required capabilities via a sidecar JSON file
//! (e.g., `slack.capabilities.json`). This module defines the schema for those files
//! and provides conversion to runtime [`Capabilities`].
//!
//! # Example Capabilities File
//!
//! ```json
//! {
//!   "http": {
//!     "allowlist": [
//!       { "host": "slack.com", "path_prefix": "/api/", "methods": ["GET", "POST"] }
//!     ],
//!     "credentials": {
//!       "slack_bot_token": {
//!         "secret_name": "slack_bot_token",
//!         "location": { "type": "bearer" },
//!         "host_patterns": ["slack.com"]
//!       }
//!     },
//!     "rate_limit": { "requests_per_minute": 50, "requests_per_hour": 1000 }
//!   },
//!   "secrets": {
//!     "allowed_names": ["slack_bot_token"]
//!   }
//! }
//! ```

use std::collections::HashMap;
use std::time::Duration;

use serde::{Deserialize, Serialize};

use crate::secrets::{CredentialLocation, CredentialMapping};
use crate::tools::wasm::{
    Capabilities, EndpointPattern, HttpCapability, RateLimitConfig, SecretsCapability,
    ToolInvokeCapability, WebhookCapability, WorkspaceCapability,
};

/// Root schema for a capabilities JSON file.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CapabilitiesFile {
    /// Human-readable description of what the tool does.
    /// Used as the `Tool::description()` return value.
    /// If omitted, a generic fallback is used (with a warning).
    #[serde(default)]
    pub description: Option<String>,

    /// Extension version (semver).
    #[serde(default)]
    pub version: Option<String>,

    /// WIT interface version this extension was compiled against (semver).
    #[serde(default)]
    pub wit_version: Option<String>,

    /// HTTP request capability.
    #[serde(default)]
    pub http: Option<HttpCapabilitySchema>,

    /// Secret existence checks.
    #[serde(default)]
    pub secrets: Option<SecretsCapabilitySchema>,

    /// Tool invocation via aliases.
    #[serde(default)]
    pub tool_invoke: Option<ToolInvokeCapabilitySchema>,

    /// Workspace file read access.
    #[serde(default)]
    pub workspace: Option<WorkspaceCapabilitySchema>,

    /// Tool webhook authentication/signature configuration.
    #[serde(default)]
    pub webhook: Option<WebhookCapabilitySchema>,

    /// Arbitrary websocket configuration preserved for runtime consumers.
    #[serde(default)]
    pub websocket: Option<serde_json::Value>,

    /// Authentication setup instructions.
    /// Used by `ironclaw config` to guide users through auth setup.
    #[serde(default)]
    pub auth: Option<AuthCapabilitySchema>,

    /// Setup schema: secrets the user must provide before the tool can be used.
    /// Mirrors the channel `setup.required_secrets` pattern.
    #[serde(default)]
    pub setup: Option<ToolSetupSchema>,

    /// Nested capabilities wrapper for channel-level JSON compatibility.
    ///
    /// Channel capabilities files nest tool capabilities under a `"capabilities"` key.
    /// This allows `from_json()`/`from_bytes()` to also parse channel-level JSON;
    /// inner fields are promoted into top-level fields by `resolve_nested()`.
    /// Always `None` after construction via the public parse methods.
    #[serde(default, skip_serializing)]
    pub capabilities: Option<Box<CapabilitiesFile>>,
}

/// Maximum length for the description field to prevent memory abuse.
const MAX_DESCRIPTION_CHARS: usize = 4096;
impl CapabilitiesFile {
    /// Parse from JSON string.
    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        let mut caps = serde_json::from_str::<Self>(json).map(Self::resolve_nested)?;
        caps.enforce_limits();
        Ok(caps)
    }

    /// Parse from JSON bytes.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
        let mut caps = serde_json::from_slice::<Self>(bytes).map(Self::resolve_nested)?;
        caps.enforce_limits();
        Ok(caps)
    }

    /// Truncate oversized fields to prevent unbounded memory usage.
    fn enforce_limits(&mut self) {
        // Truncate oversized description (issue #976)
        if let Some(ref desc) = self.description
            && desc.len() > MAX_DESCRIPTION_CHARS
        {
            let truncated = &desc[..desc.floor_char_boundary(MAX_DESCRIPTION_CHARS)];
            tracing::warn!(
                "Capabilities description truncated from {} to {} chars",
                desc.len(),
                MAX_DESCRIPTION_CHARS,
            );
            self.description = Some(truncated.to_string());
        }
    }

    /// Merge nested `capabilities` wrapper into top-level fields.
    ///
    /// Channel-level JSON nests tool capabilities under `"capabilities"`.
    /// This promotes the inner fields so callers can access them uniformly.
    /// Maximum nesting depth for capabilities resolution.
    const MAX_NESTED_DEPTH: usize = 8;

    fn resolve_nested(self) -> Self {
        self.resolve_nested_inner(0)
    }

    fn resolve_nested_inner(mut self, depth: usize) -> Self {
        if depth > Self::MAX_NESTED_DEPTH {
            tracing::warn!(
                "Capabilities nesting exceeds maximum depth of {}, stopping resolution",
                Self::MAX_NESTED_DEPTH
            );
            return self;
        }
        if let Some(inner) = self.capabilities.take() {
            let inner = inner.resolve_nested_inner(depth + 1);
            self.description = self.description.or(inner.description);
            self.http = self.http.or(inner.http);
            self.secrets = self.secrets.or(inner.secrets);
            self.tool_invoke = self.tool_invoke.or(inner.tool_invoke);
            self.workspace = self.workspace.or(inner.workspace);
            self.webhook = self.webhook.or(inner.webhook);
            self.websocket = self.websocket.or(inner.websocket);
            self.auth = self.auth.or(inner.auth);
            self.setup = self.setup.or(inner.setup);
        }
        self
    }

    /// Validate the capabilities file and emit warnings for common misconfigurations.
    ///
    /// Called once at load time to catch issues early. Warnings are emitted via
    /// `tracing::warn` so they show up in startup logs without blocking loading.
    pub fn validate(&self, name: &str) {
        const MIN_PROMPT_LENGTH: usize = 30;

        // setup.required_secrets present but no auth section → auth card won't display
        if let Some(setup) = &self.setup {
            if !setup.required_secrets.is_empty() && self.auth.is_none() {
                tracing::warn!(
                    tool = name,
                    "setup.required_secrets defined but no 'auth' section — \
                     chat-based auth card will not display for this tool"
                );
            }

            // Check for short prompts
            for secret in &setup.required_secrets {
                if secret.prompt.len() < MIN_PROMPT_LENGTH {
                    tracing::warn!(
                        tool = name,
                        secret = secret.name,
                        prompt = secret.prompt,
                        "setup.required_secrets prompt is shorter than {} chars — \
                         consider a more descriptive prompt that tells the user where to find this value",
                        MIN_PROMPT_LENGTH
                    );
                }
            }
        }

        // Manual auth (no OAuth) checks
        if let Some(auth) = &self.auth
            && auth.oauth.is_none()
        {
            if auth.setup_url.is_none() {
                tracing::warn!(
                    tool = name,
                    "auth section has no OAuth and no setup_url — \
                     user has no link to obtain credentials"
                );
            }
            if auth.instructions.is_none() {
                tracing::warn!(
                    tool = name,
                    "auth section has no OAuth and no instructions — \
                     user has no guidance on how to obtain credentials"
                );
            }
        }
    }

    /// Convert to runtime Capabilities.
    pub fn to_capabilities(&self) -> Capabilities {
        let mut caps = Capabilities::default();

        if let Some(http) = &self.http {
            caps.http = Some(http.to_http_capability());
        }

        if let Some(secrets) = &self.secrets {
            caps.secrets = Some(SecretsCapability {
                allowed_names: secrets.allowed_names.clone(),
            });
        }

        if let Some(tool_invoke) = &self.tool_invoke {
            caps.tool_invoke = Some(ToolInvokeCapability {
                aliases: tool_invoke.aliases.clone(),
                rate_limit: tool_invoke
                    .rate_limit
                    .as_ref()
                    .map(|r| r.to_rate_limit_config())
                    .unwrap_or_default(),
            });
        }

        if let Some(workspace) = &self.workspace {
            caps.workspace_read = Some(WorkspaceCapability {
                allowed_prefixes: workspace.allowed_prefixes.clone(),
                reader: None, // Injected at runtime
            });
        }

        if let Some(webhook) = &self.webhook {
            caps.webhook = Some(webhook.to_webhook_capability());
        }

        caps.websocket = self.websocket.clone();

        caps
    }
}

/// HTTP capability schema.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct HttpCapabilitySchema {
    /// Allowed endpoint patterns.
    #[serde(default)]
    pub allowlist: Vec<EndpointPatternSchema>,

    /// Credential mappings (key is an identifier, not the secret name).
    #[serde(default)]
    pub credentials: HashMap<String, CredentialMappingSchema>,

    /// Rate limiting configuration.
    #[serde(default)]
    pub rate_limit: Option<RateLimitSchema>,

    /// Maximum request body size in bytes.
    #[serde(default)]
    pub max_request_bytes: Option<usize>,

    /// Maximum response body size in bytes.
    #[serde(default)]
    pub max_response_bytes: Option<usize>,

    /// Request timeout in seconds.
    #[serde(default)]
    pub timeout_secs: Option<u64>,
}

impl HttpCapabilitySchema {
    fn to_http_capability(&self) -> HttpCapability {
        let mut cap = HttpCapability {
            allowlist: self
                .allowlist
                .iter()
                .map(|p| p.to_endpoint_pattern())
                .collect(),
            credentials: self
                .credentials
                .values()
                .map(|m| (m.secret_name.clone(), m.to_credential_mapping()))
                .collect(),
            rate_limit: self
                .rate_limit
                .as_ref()
                .map(|r| r.to_rate_limit_config())
                .unwrap_or_default(),
            ..Default::default()
        };

        if let Some(max) = self.max_request_bytes {
            cap.max_request_bytes = max;
        }
        if let Some(max) = self.max_response_bytes {
            cap.max_response_bytes = max;
        }
        if let Some(secs) = self.timeout_secs {
            cap.timeout = Duration::from_secs(secs);
        }

        cap
    }
}

/// Endpoint pattern schema.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EndpointPatternSchema {
    /// Hostname (e.g., "api.slack.com" or "*.slack.com").
    pub host: String,

    /// Optional path prefix (e.g., "/api/").
    #[serde(default)]
    pub path_prefix: Option<String>,

    /// Allowed HTTP methods (empty = all).
    #[serde(default)]
    pub methods: Vec<String>,
}

impl EndpointPatternSchema {
    fn to_endpoint_pattern(&self) -> EndpointPattern {
        EndpointPattern {
            host: self.host.clone(),
            path_prefix: self.path_prefix.clone(),
            methods: self.methods.clone(),
        }
    }
}

/// Credential mapping schema.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CredentialMappingSchema {
    /// Name of the secret to inject.
    pub secret_name: String,

    /// Where to inject the credential.
    pub location: CredentialLocationSchema,

    /// Host patterns this credential applies to.
    #[serde(default)]
    pub host_patterns: Vec<String>,
}

impl CredentialMappingSchema {
    fn to_credential_mapping(&self) -> CredentialMapping {
        CredentialMapping {
            secret_name: self.secret_name.clone(),
            location: self.location.to_credential_location(),
            host_patterns: self.host_patterns.clone(),
        }
    }
}

/// Credential injection location schema.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum CredentialLocationSchema {
    /// Bearer token in Authorization header.
    Bearer,

    /// Basic auth (password from secret, username in config).
    Basic { username: String },

    /// Custom header.
    Header {
        #[serde(alias = "header_name")]
        name: String,
        #[serde(default)]
        prefix: Option<String>,
    },

    /// Query parameter.
    QueryParam { name: String },

    /// URL/path placeholder replacement.
    UrlPath { placeholder: String },
}

impl CredentialLocationSchema {
    fn to_credential_location(&self) -> CredentialLocation {
        match self {
            CredentialLocationSchema::Bearer => CredentialLocation::AuthorizationBearer,
            CredentialLocationSchema::Basic { username } => {
                CredentialLocation::AuthorizationBasic {
                    username: username.clone(),
                }
            }
            CredentialLocationSchema::Header { name, prefix } => CredentialLocation::Header {
                name: name.clone(),
                prefix: prefix.clone(),
            },
            CredentialLocationSchema::QueryParam { name } => {
                CredentialLocation::QueryParam { name: name.clone() }
            }
            CredentialLocationSchema::UrlPath { placeholder } => CredentialLocation::UrlPath {
                placeholder: placeholder.clone(),
            },
        }
    }
}

/// Rate limit schema.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitSchema {
    /// Maximum requests per minute.
    #[serde(default = "default_requests_per_minute")]
    pub requests_per_minute: u32,

    /// Maximum requests per hour.
    #[serde(default = "default_requests_per_hour")]
    pub requests_per_hour: u32,
}

fn default_requests_per_minute() -> u32 {
    60
}

fn default_requests_per_hour() -> u32 {
    1000
}

impl RateLimitSchema {
    fn to_rate_limit_config(&self) -> RateLimitConfig {
        RateLimitConfig {
            requests_per_minute: self.requests_per_minute,
            requests_per_hour: self.requests_per_hour,
        }
    }
}

/// Secrets capability schema.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SecretsCapabilitySchema {
    /// Secret names the tool can check existence of (supports glob).
    #[serde(default)]
    pub allowed_names: Vec<String>,
}

/// Tool invocation capability schema.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ToolInvokeCapabilitySchema {
    /// Mapping from alias to real tool name.
    #[serde(default)]
    pub aliases: HashMap<String, String>,

    /// Rate limiting for tool calls.
    #[serde(default)]
    pub rate_limit: Option<RateLimitSchema>,
}

/// Workspace read capability schema.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct WorkspaceCapabilitySchema {
    /// Allowed path prefixes (e.g., ["context/", "daily/"]).
    #[serde(default)]
    pub allowed_prefixes: Vec<String>,
}

/// Webhook capability schema for tools.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct WebhookCapabilitySchema {
    /// HTTP header name for secret validation.
    #[serde(default)]
    pub secret_header: Option<String>,
    /// Secret name in secrets store for shared-secret validation.
    #[serde(default)]
    pub secret_name: Option<String>,
    /// Secret name in secrets store containing Ed25519 public key.
    #[serde(default)]
    pub signature_key_secret_name: Option<String>,
    /// Secret name in secrets store for HMAC-SHA256 signing.
    #[serde(default)]
    pub hmac_secret_name: Option<String>,
    /// Signature header for HMAC verification.
    #[serde(default)]
    pub hmac_signature_header: Option<String>,
    /// Optional timestamp header for Slack-style v0 verification.
    #[serde(default)]
    pub hmac_timestamp_header: Option<String>,
    /// Optional signature prefix for body-only HMAC mode (default sha256=).
    #[serde(default)]
    pub hmac_prefix: Option<String>,
}

impl WebhookCapabilitySchema {
    fn to_webhook_capability(&self) -> WebhookCapability {
        WebhookCapability {
            secret_header: self.secret_header.clone(),
            secret_name: self.secret_name.clone(),
            signature_key_secret_name: self.signature_key_secret_name.clone(),
            hmac_secret_name: self.hmac_secret_name.clone(),
            hmac_signature_header: self.hmac_signature_header.clone(),
            hmac_timestamp_header: self.hmac_timestamp_header.clone(),
            hmac_prefix: self.hmac_prefix.clone(),
        }
    }
}

/// Authentication setup schema.
///
/// Tools declare their auth requirements here. The agent uses this to provide
/// generic auth flows without needing service-specific code in the main codebase.
///
/// Supports two auth methods:
/// 1. **OAuth** - Browser-based login (preferred for user-facing services)
/// 2. **Manual** - Copy/paste token from provider's dashboard
///
/// # Example (OAuth)
///
/// ```json
/// {
///   "auth": {
///     "secret_name": "notion_api_token",
///     "display_name": "Notion",
///     "oauth": {
///       "authorization_url": "https://api.notion.com/v1/oauth/authorize",
///       "token_url": "https://api.notion.com/v1/oauth/token",
///       "client_id": "your-client-id",
///       "scopes": []
///     },
///     "env_var": "NOTION_TOKEN"
///   }
/// }
/// ```
///
/// # Example (Manual)
///
/// ```json
/// {
///   "auth": {
///     "secret_name": "openai_api_key",
///     "display_name": "OpenAI",
///     "instructions": "Get your API key from platform.openai.com/api-keys",
///     "setup_url": "https://platform.openai.com/api-keys",
///     "token_hint": "Starts with 'sk-'",
///     "env_var": "OPENAI_API_KEY"
///   }
/// }
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AuthCapabilitySchema {
    /// Name of the secret to store (e.g., "notion_api_token").
    /// Must match the secret_name in credentials if HTTP capability is used.
    pub secret_name: String,

    /// Human-readable name for the service (e.g., "Notion", "Slack").
    #[serde(default)]
    pub display_name: Option<String>,

    /// OAuth configuration for browser-based login.
    /// If present, OAuth flow is used instead of manual token entry.
    #[serde(default)]
    pub oauth: Option<OAuthConfigSchema>,

    /// Instructions shown to the user for obtaining credentials (manual flow).
    /// Can include markdown formatting.
    #[serde(default)]
    pub instructions: Option<String>,

    /// URL to open for setting up credentials (manual flow).
    #[serde(default)]
    pub setup_url: Option<String>,

    /// Hint about expected token format (e.g., "Starts with 'sk-'").
    /// Used for validation feedback.
    #[serde(default)]
    pub token_hint: Option<String>,

    /// Environment variable to check before prompting.
    /// If this env var is set, its value is used automatically.
    #[serde(default)]
    pub env_var: Option<String>,

    /// Provider hint for organizing secrets (e.g., "notion", "openai").
    #[serde(default)]
    pub provider: Option<String>,

    /// Validation endpoint to check if the token works.
    /// Tool can specify an endpoint to call for validation.
    #[serde(default)]
    pub validation_endpoint: Option<ValidationEndpointSchema>,
}

/// OAuth 2.0 configuration for browser-based login.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct OAuthConfigSchema {
    /// OAuth authorization URL (e.g., "https://api.notion.com/v1/oauth/authorize").
    pub authorization_url: String,

    /// OAuth token exchange URL (e.g., "https://api.notion.com/v1/oauth/token").
    pub token_url: String,

    /// OAuth client ID.
    /// Can be set here or via environment variable (see client_id_env).
    #[serde(default)]
    pub client_id: Option<String>,

    /// Environment variable containing the client ID.
    /// Checked if client_id is not set directly.
    #[serde(default)]
    pub client_id_env: Option<String>,

    /// OAuth client secret (optional, some providers don't require it with PKCE).
    /// Can be set here or via environment variable (see client_secret_env).
    #[serde(default)]
    pub client_secret: Option<String>,

    /// Environment variable containing the client secret.
    /// Checked if client_secret is not set directly.
    #[serde(default)]
    pub client_secret_env: Option<String>,

    /// OAuth scopes to request.
    #[serde(default)]
    pub scopes: Vec<String>,

    /// Use PKCE (Proof Key for Code Exchange). Defaults to true.
    /// Required for public clients (CLI tools).
    #[serde(default = "default_true")]
    pub use_pkce: bool,

    /// Additional parameters to include in the authorization URL.
    #[serde(default)]
    pub extra_params: std::collections::HashMap<String, String>,

    /// Field name in token response containing the access token.
    /// Defaults to "access_token".
    #[serde(default = "default_access_token_field")]
    pub access_token_field: String,
}

fn default_true() -> bool {
    true
}

fn default_access_token_field() -> String {
    "access_token".to_string()
}

/// Schema for token validation endpoint.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ValidationEndpointSchema {
    /// URL to call for validation (e.g., "https://api.notion.com/v1/users/me").
    pub url: String,

    /// HTTP method (defaults to GET).
    #[serde(default = "default_method")]
    pub method: String,

    /// Expected HTTP status code for success (defaults to 200).
    #[serde(default = "default_success_status")]
    pub success_status: u16,

    /// Additional headers to send with the validation request.
    /// Used for service-specific requirements (e.g., Notion-Version for Notion API).
    #[serde(default)]
    pub headers: HashMap<String, String>,
}

fn default_method() -> String {
    "GET".to_string()
}

fn default_success_status() -> u16 {
    200
}

/// Setup schema for WASM tools: secrets the user must provide via the UI.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ToolSetupSchema {
    /// Secrets the user must provide before the tool can be used.
    #[serde(default)]
    pub required_secrets: Vec<ToolSecretSetupSchema>,
    /// Non-secret fields the user can configure in the setup modal.
    #[serde(default)]
    pub required_fields: Vec<ToolFieldSetupSchema>,
}

/// A single secret required during tool setup.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolSecretSetupSchema {
    /// Secret name in the secrets store (e.g. "google_oauth_client_id").
    pub name: String,
    /// User-facing prompt (e.g. "Google OAuth Client ID").
    pub prompt: String,
    /// If true, the user may skip this secret.
    #[serde(default)]
    pub optional: bool,
}

/// A non-secret field required during tool setup.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolFieldSetupSchema {
    /// Field name in setup payload.
    pub name: String,
    /// User-facing prompt shown in the setup modal.
    pub prompt: String,
    /// If true, the user may skip this field.
    #[serde(default)]
    pub optional: bool,
    /// Input type used in the setup modal.
    #[serde(default = "default_tool_setup_field_input_type")]
    pub input_type: ToolSetupFieldInputType,
    /// Optional dotted setting path to persist this value to.
    ///
    /// Restricted by the host to extension-owned namespaces and a small
    /// allowlist of approved global settings.
    ///
    /// Example: `extensions.switch-llm.provider`, `llm_backend`, or
    /// `selected_model`.
    #[serde(default)]
    pub setting_path: Option<String>,
    /// Whether changing this field requires a restart to fully apply.
    #[serde(default)]
    pub restart_required: bool,
}

/// Input widget type for a setup field.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ToolSetupFieldInputType {
    #[default]
    Text,
    Password,
}

fn default_tool_setup_field_input_type() -> ToolSetupFieldInputType {
    ToolSetupFieldInputType::Text
}

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

    use crate::tools::wasm::capabilities_schema::{CapabilitiesFile, CredentialLocationSchema};

    #[test]
    fn test_parse_minimal() {
        let json = "{}";
        let caps = CapabilitiesFile::from_json(json).unwrap();
        assert!(caps.http.is_none());
        assert!(caps.secrets.is_none());
    }

    #[test]
    fn test_parse_http_allowlist() {
        let json = r#"{
            "http": {
                "allowlist": [
                    { "host": "api.slack.com", "path_prefix": "/api/", "methods": ["GET", "POST"] }
                ]
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        let http = caps.http.unwrap();
        assert_eq!(http.allowlist.len(), 1);
        assert_eq!(http.allowlist[0].host, "api.slack.com");
        assert_eq!(http.allowlist[0].path_prefix, Some("/api/".to_string()));
        assert_eq!(http.allowlist[0].methods, vec!["GET", "POST"]);
    }

    #[test]
    fn test_parse_credentials() {
        let json = r#"{
            "http": {
                "allowlist": [{ "host": "slack.com" }],
                "credentials": {
                    "slack": {
                        "secret_name": "slack_bot_token",
                        "location": { "type": "bearer" },
                        "host_patterns": ["slack.com", "*.slack.com"]
                    }
                }
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        let http = caps.http.unwrap();
        assert_eq!(http.credentials.len(), 1);
        let cred = http.credentials.get("slack").unwrap();
        assert_eq!(cred.secret_name, "slack_bot_token");
        assert!(matches!(cred.location, CredentialLocationSchema::Bearer));
        assert_eq!(cred.host_patterns, vec!["slack.com", "*.slack.com"]);
    }

    #[test]
    fn test_parse_custom_header_credential() {
        let json = r#"{
            "http": {
                "allowlist": [{ "host": "api.example.com" }],
                "credentials": {
                    "api_key": {
                        "secret_name": "my_api_key",
                        "location": { "type": "header", "name": "X-API-Key", "prefix": "Key " },
                        "host_patterns": ["api.example.com"]
                    }
                }
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        let http = caps.http.unwrap();
        let cred = http.credentials.get("api_key").unwrap();
        match &cred.location {
            CredentialLocationSchema::Header { name, prefix } => {
                assert_eq!(name, "X-API-Key");
                assert_eq!(prefix, &Some("Key ".to_string()));
            }
            _ => panic!("Expected Header location"),
        }
    }

    #[test]
    fn test_parse_url_path_credential() {
        let json = r#"{
            "http": {
                "allowlist": [{ "host": "api.telegram.org" }],
                "credentials": {
                    "telegram_bot": {
                        "secret_name": "telegram_bot_token",
                        "location": {
                            "type": "url_path",
                            "placeholder": "{TELEGRAM_BOT_TOKEN}"
                        },
                        "host_patterns": ["api.telegram.org"]
                    }
                }
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        let http = caps.http.unwrap();
        let cred = http.credentials.get("telegram_bot").unwrap();
        match &cred.location {
            CredentialLocationSchema::UrlPath { placeholder } => {
                assert_eq!(placeholder, "{TELEGRAM_BOT_TOKEN}");
            }
            _ => panic!("Expected UrlPath location"),
        }
    }

    #[test]
    fn test_parse_secrets_capability() {
        let json = r#"{
            "secrets": {
                "allowed_names": ["slack_*", "openai_key"]
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        let secrets = caps.secrets.unwrap();
        assert_eq!(secrets.allowed_names, vec!["slack_*", "openai_key"]);
    }

    #[test]
    fn test_parse_tool_invoke() {
        let json = r#"{
            "tool_invoke": {
                "aliases": {
                    "search": "brave_search",
                    "calc": "calculator"
                },
                "rate_limit": {
                    "requests_per_minute": 10,
                    "requests_per_hour": 100
                }
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        let tool_invoke = caps.tool_invoke.unwrap();
        assert_eq!(
            tool_invoke.aliases.get("search"),
            Some(&"brave_search".to_string())
        );
        let rate = tool_invoke.rate_limit.unwrap();
        assert_eq!(rate.requests_per_minute, 10);
    }

    #[test]
    fn test_parse_workspace() {
        let json = r#"{
            "workspace": {
                "allowed_prefixes": ["context/", "daily/"]
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        let workspace = caps.workspace.unwrap();
        assert_eq!(workspace.allowed_prefixes, vec!["context/", "daily/"]);
    }

    #[test]
    fn test_parse_webhook_capability() {
        let json = r#"{
            "webhook": {
                "hmac_secret_name": "github_webhook_secret",
                "hmac_signature_header": "x-hub-signature-256",
                "hmac_prefix": "sha256="
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        let webhook = caps.webhook.unwrap();
        assert_eq!(
            webhook.hmac_secret_name.as_deref(),
            Some("github_webhook_secret")
        );
        assert_eq!(
            webhook.hmac_signature_header.as_deref(),
            Some("x-hub-signature-256")
        );
    }

    #[test]
    fn test_to_capabilities() {
        let json = r#"{
            "http": {
                "allowlist": [{ "host": "api.slack.com", "path_prefix": "/api/" }],
                "rate_limit": { "requests_per_minute": 50, "requests_per_hour": 500 }
            },
            "secrets": {
                "allowed_names": ["slack_token"]
            }
        }"#;

        let file = CapabilitiesFile::from_json(json).unwrap();
        let caps = file.to_capabilities();

        assert!(caps.http.is_some());
        let http = caps.http.unwrap();
        assert_eq!(http.allowlist.len(), 1);
        assert_eq!(http.rate_limit.requests_per_minute, 50);

        assert!(caps.secrets.is_some());
        let secrets = caps.secrets.unwrap();
        assert!(secrets.is_allowed("slack_token"));
    }

    #[test]
    fn test_full_slack_example() {
        let json = r#"{
            "http": {
                "allowlist": [
                    { "host": "slack.com", "path_prefix": "/api/", "methods": ["GET", "POST"] }
                ],
                "credentials": {
                    "slack_bot_token": {
                        "secret_name": "slack_bot_token",
                        "location": { "type": "bearer" },
                        "host_patterns": ["slack.com"]
                    }
                },
                "rate_limit": { "requests_per_minute": 50, "requests_per_hour": 1000 }
            },
            "secrets": {
                "allowed_names": ["slack_bot_token"]
            }
        }"#;

        let file = CapabilitiesFile::from_json(json).unwrap();
        let caps = file.to_capabilities();

        let http = caps.http.unwrap();
        assert_eq!(http.allowlist[0].host, "slack.com");
        assert!(http.credentials.contains_key("slack_bot_token"));

        let secrets = caps.secrets.unwrap();
        assert!(secrets.is_allowed("slack_bot_token"));
    }

    #[test]
    fn test_parse_auth_capability() {
        let json = r#"{
            "auth": {
                "secret_name": "notion_api_token",
                "display_name": "Notion",
                "instructions": "Create an integration at notion.so/my-integrations",
                "setup_url": "https://www.notion.so/my-integrations",
                "token_hint": "Starts with 'secret_' or 'ntn_'",
                "env_var": "NOTION_TOKEN",
                "provider": "notion",
                "validation_endpoint": {
                    "url": "https://api.notion.com/v1/users/me",
                    "method": "GET",
                    "success_status": 200
                }
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        let auth = caps.auth.unwrap();
        assert_eq!(auth.secret_name, "notion_api_token");
        assert_eq!(auth.display_name, Some("Notion".to_string()));
        assert_eq!(auth.env_var, Some("NOTION_TOKEN".to_string()));
        assert_eq!(auth.provider, Some("notion".to_string()));

        let validation = auth.validation_endpoint.unwrap();
        assert_eq!(validation.url, "https://api.notion.com/v1/users/me");
        assert_eq!(validation.method, "GET");
        assert_eq!(validation.success_status, 200);
    }

    #[test]
    fn test_parse_auth_minimal() {
        let json = r#"{
            "auth": {
                "secret_name": "my_api_key"
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        let auth = caps.auth.unwrap();
        assert_eq!(auth.secret_name, "my_api_key");
        assert!(auth.display_name.is_none());
        assert!(auth.setup_url.is_none());
    }

    // ── Category 1: Header field name alias ─────────────────────────────

    #[test]
    fn test_header_location_with_name_field() {
        let json = r#"{
            "http": {
                "allowlist": [{ "host": "discord.com" }],
                "credentials": {
                    "bot_token": {
                        "secret_name": "discord_bot_token",
                        "location": { "type": "header", "name": "Authorization", "prefix": "Bot " },
                        "host_patterns": ["discord.com"]
                    }
                }
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        let http = caps.http.unwrap();
        let cred = http.credentials.get("bot_token").unwrap();
        match &cred.location {
            CredentialLocationSchema::Header { name, prefix } => {
                assert_eq!(name, "Authorization");
                assert_eq!(prefix, &Some("Bot ".to_string()));
            }
            _ => panic!("Expected Header location"),
        }
    }

    #[test]
    fn test_header_location_with_header_name_alias() {
        // Uses "header_name" instead of "name" — should parse via serde alias
        let json = r#"{
            "http": {
                "allowlist": [{ "host": "discord.com" }],
                "credentials": {
                    "bot_token": {
                        "secret_name": "discord_bot_token",
                        "location": { "type": "header", "header_name": "Authorization", "prefix": "Bot " },
                        "host_patterns": ["discord.com"]
                    }
                }
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        let http = caps.http.unwrap();
        let cred = http.credentials.get("bot_token").unwrap();
        match &cred.location {
            CredentialLocationSchema::Header { name, prefix } => {
                assert_eq!(name, "Authorization");
                assert_eq!(prefix, &Some("Bot ".to_string()));
            }
            _ => panic!("Expected Header location"),
        }
    }

    #[test]
    fn test_discord_capabilities_file_parses() {
        // Full Discord capabilities JSON — tests end-to-end parsing
        let json = r#"{
            "type": "channel",
            "name": "discord",
            "description": "Discord channel",
            "setup": {
                "required_secrets": [
                    {
                        "name": "discord_bot_token",
                        "prompt": "Enter your Discord Bot Token",
                        "optional": false
                    },
                    {
                        "name": "discord_public_key",
                        "prompt": "Enter your Discord Public Key",
                        "optional": false
                    }
                ]
            },
            "capabilities": {
                "http": {
                    "allowlist": [{ "host": "discord.com", "path_prefix": "/api/v10" }],
                    "credentials": {
                        "discord_bot_token": {
                            "secret_name": "discord_bot_token",
                            "location": { "type": "header", "name": "Authorization", "prefix": "Bot " },
                            "host_patterns": ["discord.com"]
                        }
                    }
                }
            },
            "config": {
                "require_signature_verification": true
            }
        }"#;

        // This must not panic — parsing should succeed
        let caps = CapabilitiesFile::from_json(json).unwrap();
        let http = caps.http.unwrap();
        assert!(http.credentials.contains_key("discord_bot_token"));
    }

    #[test]
    fn test_header_location_missing_name_fails() {
        // Neither "name" nor "header_name" provided — should fail
        let json = r#"{
            "http": {
                "allowlist": [{ "host": "example.com" }],
                "credentials": {
                    "api_key": {
                        "secret_name": "my_key",
                        "location": { "type": "header", "prefix": "Key " },
                        "host_patterns": ["example.com"]
                    }
                }
            }
        }"#;

        assert!(
            CapabilitiesFile::from_json(json).is_err(),
            "Header without name or header_name should fail deserialization"
        );
    }

    // ── resolve_nested tests ──────────────────────────────────────────

    #[test]
    fn test_resolve_nested_outer_takes_precedence() {
        // Outer http should win over inner http
        let json = r#"{
            "http": {
                "allowlist": [{ "host": "outer.example.com" }]
            },
            "capabilities": {
                "http": {
                    "allowlist": [{ "host": "inner.example.com" }]
                }
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        let http = caps.http.unwrap();
        assert_eq!(
            http.allowlist[0].host, "outer.example.com",
            "Outer http should take precedence over inner"
        );
    }

    #[test]
    fn test_resolve_nested_doubly_nested() {
        // capabilities.capabilities.http should resolve to top-level
        let json = r#"{
            "capabilities": {
                "capabilities": {
                    "http": {
                        "allowlist": [{ "host": "deep.example.com" }]
                    }
                }
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        let http = caps.http.unwrap();
        assert_eq!(
            http.allowlist[0].host, "deep.example.com",
            "Doubly-nested capabilities should be resolved"
        );
    }

    #[test]
    fn test_resolve_nested_all_fields_promoted() {
        // Inner has secrets, workspace, and auth — all should be promoted
        let json = r#"{
            "capabilities": {
                "secrets": {
                    "allowed_names": ["my_secret"]
                },
                "workspace": {
                    "allowed_prefixes": ["data/"]
                },
                "auth": {
                    "secret_name": "my_auth_token"
                }
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        assert!(caps.secrets.is_some(), "secrets should be promoted");
        assert!(caps.workspace.is_some(), "workspace should be promoted");
        assert!(caps.auth.is_some(), "auth should be promoted");

        assert_eq!(caps.secrets.unwrap().allowed_names, vec!["my_secret"]);
        assert_eq!(caps.workspace.unwrap().allowed_prefixes, vec!["data/"]);
        assert_eq!(caps.auth.unwrap().secret_name, "my_auth_token");
    }

    #[test]
    fn test_parse_tool_setup_schema() {
        let json = r#"{
            "setup": {
                "required_secrets": [
                    {
                        "name": "google_oauth_client_id",
                        "prompt": "Google OAuth Client ID"
                    },
                    {
                        "name": "google_oauth_client_secret",
                        "prompt": "Google OAuth Client Secret",
                        "optional": true
                    }
                ],
                "required_fields": [
                    {
                        "name": "llm_backend",
                        "prompt": "LLM Provider",
                        "setting_path": "llm_backend",
                        "restart_required": true
                    },
                    {
                        "name": "selected_model",
                        "prompt": "Model Name",
                        "input_type": "text",
                        "setting_path": "selected_model"
                    }
                ]
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        let setup = caps.setup.unwrap();
        assert_eq!(setup.required_secrets.len(), 2);
        assert_eq!(setup.required_secrets[0].name, "google_oauth_client_id");
        assert_eq!(setup.required_secrets[0].prompt, "Google OAuth Client ID");
        assert!(!setup.required_secrets[0].optional);
        assert_eq!(setup.required_secrets[1].name, "google_oauth_client_secret");
        assert!(setup.required_secrets[1].optional);
        assert_eq!(setup.required_fields.len(), 2);
        assert_eq!(setup.required_fields[0].name, "llm_backend");
        assert_eq!(
            setup.required_fields[0].setting_path.as_deref(),
            Some("llm_backend")
        );
        assert!(setup.required_fields[0].restart_required);
        assert_eq!(
            setup.required_fields[0].input_type,
            crate::tools::wasm::capabilities_schema::ToolSetupFieldInputType::Text
        );
        assert_eq!(setup.required_fields[1].name, "selected_model");
    }

    #[test]
    fn test_tool_setup_field_input_type_defaults_to_text() {
        let json = r#"{
            "setup": {
                "required_fields": [
                    {
                        "name": "provider",
                        "prompt": "Provider"
                    },
                    {
                        "name": "token_hint",
                        "prompt": "Token Hint",
                        "input_type": "password"
                    }
                ]
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        let setup = caps.setup.unwrap();
        assert_eq!(
            setup.required_fields[0].input_type,
            crate::tools::wasm::capabilities_schema::ToolSetupFieldInputType::Text
        );
        assert_eq!(
            setup.required_fields[1].input_type,
            crate::tools::wasm::capabilities_schema::ToolSetupFieldInputType::Password
        );
    }

    #[test]
    fn test_resolve_nested_setup_promoted() {
        // setup inside capabilities wrapper should be promoted to top level
        let json = r#"{
            "capabilities": {
                "setup": {
                    "required_secrets": [
                        { "name": "my_secret", "prompt": "Enter secret" }
                    ]
                }
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        assert!(
            caps.setup.is_some(),
            "setup should be promoted from inner capabilities"
        );
        assert_eq!(caps.setup.unwrap().required_secrets[0].name, "my_secret");
    }

    #[test]
    fn test_validate_setup_without_auth_warns() {
        // setup.required_secrets with no auth section — should not panic
        let json = r#"{
            "setup": {
                "required_secrets": [
                    { "name": "api_key", "prompt": "Enter your API key from the provider dashboard settings page" }
                ]
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        // Should not panic; warning is emitted via tracing
        caps.validate("test-tool");
    }

    #[test]
    fn test_validate_manual_auth_missing_fields() {
        // auth without OAuth, missing setup_url and instructions
        let json = r#"{
            "auth": {
                "secret_name": "my_api_key"
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        // Should not panic; warnings emitted for missing setup_url and instructions
        caps.validate("test-tool");
    }

    #[test]
    fn test_validate_clean_tool() {
        // Well-configured tool with auth, setup_url, instructions, and good prompts
        let json = r#"{
            "auth": {
                "secret_name": "my_api_key",
                "setup_url": "https://example.com/api-keys",
                "instructions": "Go to example.com/api-keys and create a new key"
            },
            "setup": {
                "required_secrets": [
                    {
                        "name": "my_api_key",
                        "prompt": "Enter your API key from https://example.com/api-keys"
                    }
                ]
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        // Should not panic and emits no warnings (has auth, setup_url, instructions, long prompt)
        caps.validate("clean-tool");
    }

    #[test]
    fn test_resolve_nested_empty_capabilities_noop() {
        // Empty inner capabilities should not clobber outer http
        let json = r#"{
            "http": {
                "allowlist": [{ "host": "preserved.example.com" }]
            },
            "capabilities": {}
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        let http = caps.http.unwrap();
        assert_eq!(
            http.allowlist[0].host, "preserved.example.com",
            "Empty inner capabilities should not clobber outer http"
        );
    }

    #[test]
    fn test_discord_websocket_config_preserved_in_runtime_capabilities() {
        let json = r#"{
            "capabilities": {
                "http": {
                    "allowlist": [{ "host": "discord.com", "path_prefix": "/api/v10" }]
                },
                "websocket": {
                    "url": "wss://gateway.discord.gg/?v=10&encoding=json",
                    "connect_on_start": true,
                    "identify": {
                        "intents": 513,
                        "properties": {
                            "os": "linux",
                            "browser": "ironclaw",
                            "device": "ironclaw"
                        }
                    }
                }
            }
        }"#;

        let file = CapabilitiesFile::from_json(json).unwrap();
        let caps = file.to_capabilities();

        assert_eq!(
            caps.websocket,
            Some(json!({
                "url": "wss://gateway.discord.gg/?v=10&encoding=json",
                "connect_on_start": true,
                "identify": {
                    "intents": 513,
                    "properties": {
                        "os": "linux",
                        "browser": "ironclaw",
                        "device": "ironclaw"
                    }
                }
            }))
        );
    }

    // ── Tool description ────────────────────────────────────────────────

    #[test]
    fn test_parse_description() {
        let json = r#"{
            "description": "Search the web using Brave Search API"
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        assert_eq!(
            caps.description.as_deref(),
            Some("Search the web using Brave Search API")
        );
    }

    #[test]
    fn test_parse_without_description() {
        let json = r#"{
            "http": {
                "allowlist": [{ "host": "api.example.com" }]
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        assert!(
            caps.description.is_none(),
            "description should be None when not provided"
        );
    }

    #[test]
    fn test_parameters_field_silently_ignored() {
        // Backward compat: old capabilities files with "parameters" still parse.
        let json = r#"{
            "description": "A tool",
            "parameters": {
                "type": "object",
                "properties": { "action": { "type": "string" } }
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        assert_eq!(caps.description.as_deref(), Some("A tool"));
    }

    #[test]
    fn test_resolve_nested_description_promoted() {
        let json = r#"{
            "capabilities": {
                "description": "Inner tool description"
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        assert_eq!(
            caps.description.as_deref(),
            Some("Inner tool description"),
            "description should be promoted from inner capabilities"
        );
    }

    #[test]
    fn test_resolve_nested_outer_description_takes_precedence() {
        let json = r#"{
            "description": "Outer description wins",
            "capabilities": {
                "description": "Inner description loses"
            }
        }"#;

        let caps = CapabilitiesFile::from_json(json).unwrap();
        assert_eq!(
            caps.description.as_deref(),
            Some("Outer description wins"),
            "Outer description should take precedence over inner"
        );
    }

    /// Regression test for issue #974: deeply nested capabilities wrappers
    /// must not cause stack overflow. resolve_nested should stop at
    /// MAX_NESTED_DEPTH and return gracefully.
    #[test]
    fn test_resolve_nested_depth_limit() {
        // Build a capabilities file nested beyond MAX_NESTED_DEPTH (8).
        // The description is at the innermost level which is beyond the limit,
        // so it won't be resolved — the key assertion is no stack overflow.
        let mut json = r#"{ "description": "leaf" }"#.to_string();
        for _ in 0..20 {
            json = format!(r#"{{ "capabilities": {json} }}"#);
        }
        // Should not stack overflow — this is the primary assertion.
        let _caps = CapabilitiesFile::from_json(&json).unwrap();
    }

    /// Regression test for issue #976: oversized description strings are truncated.
    #[test]
    fn test_description_truncated_at_limit() {
        let long_desc = "x".repeat(10_000);
        let json = format!(r#"{{ "description": "{long_desc}" }}"#);
        let caps = CapabilitiesFile::from_json(&json).unwrap();
        let desc = caps.description.unwrap();
        assert!(
            desc.len() <= super::MAX_DESCRIPTION_CHARS + 50, // allow for minor overhead
            "description should be truncated to ~{} chars, got {}",
            super::MAX_DESCRIPTION_CHARS,
            desc.len()
        );
    }
}