agent86-core 1.2.1

The agent behind agent86: a safe agent runtime you can embed
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
//! The tool layer, ported from Python's `tools/base.py`, `tools/registry.py`, and
//! `tools/sandbox/policy.py`.
//!
//! A tool validates the model's arguments before anything runs. Invalid
//! arguments, policy violations, and I/O failures all come back as a
//! [`ToolResult`] with `ok = false` that the model can correct itself from;
//! nothing a tool does can crash the agent loop.

pub mod delegate;
pub mod exec;
pub mod files;
pub mod memory;
#[cfg(feature = "agent86ui")]
pub mod render_ui;
pub mod sandbox;
pub mod search;
pub mod secret;
pub mod skills;
pub mod web;

use crate::types::{ToolCall, ToolResult, ToolSpec};
use sandbox::Executor;
use serde_json::{json, Map, Value};
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, RwLock};
use std::time::Duration;

/// Default cap on a tool's output, in characters (Python's `max_output_bytes`).
pub const DEFAULT_MAX_OUTPUT_CHARS: usize = 100_000;

/// Why a tool call failed before producing a result.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolError {
    /// Argument validation failed; each entry is `"<field>: <message>"`.
    InvalidArguments(Vec<String>),
    /// What Python reports as an exception escaping `execute`: `"<Exception>: <message>"`.
    Raised { exception: String, message: String },
}

impl ToolError {
    fn raised(exception: &str, message: impl Into<String>) -> Self {
        Self::Raised {
            exception: exception.to_owned(),
            message: message.into(),
        }
    }

    /// The editor refused or could not answer a file request (beyond Python).
    pub fn editor(message: impl Into<String>) -> Self {
        Self::raised("OSError", message)
    }

    /// Map an I/O error onto the Python exception class it would raise.
    pub fn io(error: &std::io::Error) -> Self {
        let exception = match error.kind() {
            std::io::ErrorKind::NotFound => "FileNotFoundError",
            std::io::ErrorKind::PermissionDenied => "PermissionError",
            std::io::ErrorKind::IsADirectory => "IsADirectoryError",
            std::io::ErrorKind::NotADirectory => "NotADirectoryError",
            _ => "OSError",
        };
        Self::raised(exception, error.to_string())
    }
}

/// A tool the model can call.
pub trait Tool: Send + Sync {
    fn name(&self) -> &str;
    fn description(&self) -> &str;

    /// True if invoking the tool causes an external side effect (gated by approvals).
    fn side_effecting(&self) -> bool {
        false
    }

    /// False for a tool that must not share a parallel batch even though it is
    /// read-only, such as one that can reach the approval prompt.
    fn parallel_safe(&self) -> bool {
        true
    }

    /// Beyond Python: whether `${secret:NAME}` in this tool's string arguments is
    /// replaced by the user's secret when it runs (`crate::vault`). Only for tools
    /// that put a value where the user can see and approve it (a file write), never
    /// one that would carry it onto a command line or to a server.
    fn expands_secrets(&self) -> bool {
        false
    }

    /// The JSON Schema of the arguments, exactly as Python's pydantic models advertise it.
    fn parameters(&self) -> Value;

    /// What this call would do, shown in the approval prompt before it runs (a
    /// unified diff for a file write). Receives the raw, unvalidated arguments and
    /// must never fail; `None` means the argument summary says it all.
    fn preview(&self, _args: &Map<String, Value>, _ctx: &ToolContext) -> Option<String> {
        None
    }

    /// Beyond Python: the path this call would write if it is agent86's own
    /// configuration or skills ([`SandboxPolicy::guarded`]), as the model gave it.
    /// Such a write changes what agent86 runs from then on, so the approval gate
    /// asks about it even in `auto` mode, and declines it with nobody to ask.
    /// Receives the raw arguments and must never fail.
    fn guarded_target(&self, _args: &Map<String, Value>, _ctx: &ToolContext) -> Option<String> {
        None
    }

    /// Beyond Python: the file text this call would change, before and after, for a
    /// surface that shows a reviewable diff (an editor over ACP). Receives the raw
    /// arguments (already expanded, for a tool that [`Tool::expands_secrets`]) and
    /// must never fail; `None` when the call would not change a text file, or when
    /// either side is over [`MAX_CHANGE_TEXT_BYTES`].
    fn change(&self, _args: &Map<String, Value>, _ctx: &ToolContext) -> Option<FileChange> {
        None
    }

    /// What [`Tool::preview`] is written in (`diff`, `bash`, `python`), as Python's
    /// `preview_lexer`, so the interface can colour it.
    fn preview_lexer(&self) -> Option<&'static str> {
        None
    }

    /// Run the tool. `ToolResult::call_id` may be left empty; [`Tool::run`] fills it in.
    fn execute(
        &self,
        args: &Map<String, Value>,
        ctx: &ToolContext,
    ) -> Result<ToolResult, ToolError>;

    /// Advertise this tool to the model.
    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: self.name().to_owned(),
            description: self.description().to_owned(),
            parameters: self.parameters(),
            side_effecting: self.side_effecting(),
        }
    }

    /// Execute `call`, translating every failure into a structured result.
    fn run(&self, call: &ToolCall, ctx: &ToolContext) -> ToolResult {
        let mut result = match self.execute(&call.arguments, ctx) {
            Ok(result) => result,
            Err(ToolError::InvalidArguments(errors)) => failure(
                self.name(),
                format!(
                    "Invalid arguments for '{}': {}",
                    self.name(),
                    errors.join("; ")
                ),
            ),
            Err(ToolError::Raised { exception, message }) => {
                failure(self.name(), format!("{exception}: {message}"))
            }
        };
        if result.call_id.is_empty() {
            result.call_id = call.id.clone();
        }
        if result.name.is_empty() {
            result.name = self.name().to_owned();
        }
        result
    }
}

/// Beyond Python: the most text, in bytes, a [`FileChange`] keeps on either side.
/// Above it only the unified diff is kept, as before.
pub const MAX_CHANGE_TEXT_BYTES: usize = 256 * 1024;

/// Beyond Python: a text file's contents before and after a write, for an editor to
/// show as a diff (ACP's `diff` content). `write_file` and `edit_file` put one in
/// their result's metadata (`abs_path`, `old_text`, `new_text`, `line`) and give one
/// for the approval ([`Tool::change`]); `dispatch` and `build_preview` redact it, so
/// an expanded `${secret:NAME}` comes back as its placeholder.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileChange {
    /// Absolute, jail-resolved, without Windows' `\\?\` prefix.
    pub path: String,
    /// `None` for a new file.
    pub old_text: Option<String>,
    pub new_text: String,
    /// The first changed line, 1-based; `None` when nothing changes.
    pub line: Option<usize>,
}

impl FileChange {
    /// The change, unless either side is over [`MAX_CHANGE_TEXT_BYTES`].
    pub fn capped(target: &Path, old_text: Option<&str>, new_text: &str) -> Option<Self> {
        let over = |text: &str| text.len() > MAX_CHANGE_TEXT_BYTES;
        if over(new_text) || old_text.is_some_and(over) {
            return None;
        }
        Some(Self {
            path: display_path(target),
            old_text: old_text.map(str::to_owned),
            new_text: new_text.to_owned(),
            line: first_changed_line(old_text, new_text),
        })
    }

    /// The change with every vault value replaced by its placeholder.
    pub fn redacted(mut self, secrets: &crate::vault::SecretVault) -> Self {
        if !secrets.is_empty() {
            self.path = secrets.redact(&self.path);
            self.old_text = self.old_text.map(|text| secrets.redact(&text));
            self.new_text = secrets.redact(&self.new_text);
        }
        self
    }

    /// Put this change into a result's metadata.
    pub fn record(&self, metadata: &mut Map<String, Value>) {
        metadata.insert("abs_path".to_owned(), json!(self.path));
        metadata.insert("old_text".to_owned(), json!(self.old_text));
        metadata.insert("new_text".to_owned(), json!(self.new_text));
        metadata.insert("line".to_owned(), json!(self.line));
    }

    /// Record a write of `target` from `old_text` to `new_text` in a result's
    /// metadata: the whole change under the cap, else only where it is
    /// (`abs_path` and `line`), beside the unified diff the tool keeps anyway.
    pub fn record_write(
        target: &Path,
        old_text: Option<&str>,
        new_text: &str,
        metadata: &mut Map<String, Value>,
    ) {
        match Self::capped(target, old_text, new_text) {
            Some(change) => change.record(metadata),
            None => {
                metadata.insert("abs_path".to_owned(), json!(display_path(target)));
                metadata.insert(
                    "line".to_owned(),
                    json!(first_changed_line(old_text, new_text)),
                );
            }
        }
    }

    /// The change a result's metadata records, if it holds one.
    pub fn from_metadata(metadata: &Map<String, Value>) -> Option<Self> {
        Some(Self {
            path: metadata.get("abs_path")?.as_str()?.to_owned(),
            old_text: match metadata.get("old_text")? {
                Value::Null => None,
                value => Some(value.as_str()?.to_owned()),
            },
            new_text: metadata.get("new_text")?.as_str()?.to_owned(),
            line: metadata
                .get("line")
                .and_then(Value::as_u64)
                .and_then(|line| usize::try_from(line).ok()),
        })
    }
}

/// The first line, 1-based, where `new` differs from `old` (line 1 for a new file),
/// or `None` when they are the same.
pub fn first_changed_line(old: Option<&str>, new: &str) -> Option<usize> {
    let Some(old) = old else {
        return Some(1);
    };
    if old == new {
        return None;
    }
    let mut old_lines = old.split('\n');
    let mut new_lines = new.split('\n');
    let mut line: usize = 1;
    loop {
        match (old_lines.next(), new_lines.next()) {
            (Some(a), Some(b)) if a == b => line += 1,
            // A change at the very end (lines removed) is shown at the last line left.
            (Some(_), None) => return Some(line.saturating_sub(1).max(1)),
            _ => return Some(line),
        }
    }
}

/// A successful result with `content`.
pub fn success(name: &str, content: String) -> ToolResult {
    ToolResult {
        call_id: String::new(),
        name: name.to_owned(),
        ok: true,
        content,
        error: None,
        metadata: Map::new(),
    }
}

/// A failed result with `error`.
pub fn failure(name: &str, error: String) -> ToolResult {
    ToolResult {
        call_id: String::new(),
        name: name.to_owned(),
        ok: false,
        content: String::new(),
        error: Some(error),
        metadata: Map::new(),
    }
}

/// Validates tool arguments with pydantic's semantics and messages.
///
/// Unknown keys are ignored, as pydantic does by default.
pub struct Arguments<'a> {
    args: &'a Map<String, Value>,
    errors: Vec<String>,
}

impl<'a> Arguments<'a> {
    pub fn new(args: &'a Map<String, Value>) -> Self {
        Self {
            args,
            errors: Vec::new(),
        }
    }

    /// A string field; `default` makes it optional.
    pub fn string(&mut self, field: &str, default: Option<&str>) -> String {
        match (self.args.get(field), default) {
            (Some(Value::String(value)), _) => value.clone(),
            (Some(_), _) => {
                self.errors
                    .push(format!("{field}: Input should be a valid string"));
                String::new()
            }
            (None, Some(default)) => default.to_owned(),
            (None, None) => {
                self.errors.push(format!("{field}: Field required"));
                String::new()
            }
        }
    }

    /// An `Optional[str]` field (default `None`); `null` reads as absent.
    pub fn optional_string(&mut self, field: &str) -> Option<String> {
        match self.args.get(field) {
            None | Some(Value::Null) => None,
            Some(Value::String(value)) => Some(value.clone()),
            Some(_) => {
                self.errors
                    .push(format!("{field}: Input should be a valid string"));
                None
            }
        }
    }

    /// A `list[str]` field (default `[]`), each bad item reported under its index,
    /// as pydantic does.
    pub fn string_list(&mut self, field: &str) -> Vec<String> {
        match self.args.get(field) {
            None | Some(Value::Null) => Vec::new(),
            Some(Value::Array(items)) => {
                let mut values = Vec::new();
                for (index, item) in items.iter().enumerate() {
                    match item {
                        Value::String(text) => values.push(text.clone()),
                        _ => self
                            .errors
                            .push(format!("{field}.{index}: Input should be a valid string")),
                    }
                }
                values
            }
            Some(_) => {
                self.errors
                    .push(format!("{field}: Input should be a valid list"));
                Vec::new()
            }
        }
    }

    /// A string field accepted under any of `names` (pydantic's `AliasChoices`);
    /// the first name present wins, and errors name the first choice.
    pub fn string_alias(&mut self, names: &[&str]) -> String {
        match names.iter().find(|name| self.args.contains_key(**name)) {
            Some(name) => self.string(name, None),
            None => {
                self.errors.push(format!("{}: Field required", names[0]));
                String::new()
            }
        }
    }

    /// A boolean field with pydantic's lax parsing: `true`/`false`, `0`/`1`, and
    /// strings such as `"yes"`, `"off"`, or `"t"` in any case.
    pub fn boolean(&mut self, field: &str, default: bool) -> bool {
        const PLAIN: &str = "Input should be a valid boolean";
        const UNINTERPRETABLE: &str = "Input should be a valid boolean, unable to interpret input";
        let parsed = match self.args.get(field) {
            None => return default,
            Some(Value::Bool(flag)) => Ok(*flag),
            Some(Value::Number(number)) => {
                let value = number.as_f64().unwrap_or(f64::NAN);
                if value == 0.0 {
                    Ok(false)
                } else if value == 1.0 {
                    Ok(true)
                } else if number.is_f64() && value.fract() != 0.0 {
                    Err(PLAIN)
                } else {
                    Err(UNINTERPRETABLE)
                }
            }
            Some(Value::String(text)) => match text.to_lowercase().as_str() {
                "0" | "off" | "f" | "false" | "n" | "no" => Ok(false),
                "1" | "on" | "t" | "true" | "y" | "yes" => Ok(true),
                _ => Err(UNINTERPRETABLE),
            },
            Some(_) => Err(PLAIN),
        };
        parsed.unwrap_or_else(|message| {
            self.errors.push(format!("{field}: {message}"));
            default
        })
    }

    /// An optional `dict[str, str]` field (default `{}`), each bad value reported
    /// under its own key, as pydantic does.
    pub fn string_map(&mut self, field: &str) -> Map<String, Value> {
        match self.args.get(field) {
            None => Map::new(),
            Some(Value::Object(map)) => {
                for (key, value) in map {
                    if !value.is_string() {
                        self.errors
                            .push(format!("{field}.{key}: Input should be a valid string"));
                    }
                }
                map.clone()
            }
            Some(_) => {
                self.errors
                    .push(format!("{field}: Input should be a valid dictionary"));
                Map::new()
            }
        }
    }

    /// An `int` field with pydantic's lax parsing: integers, whole floats, booleans
    /// (as 0 and 1), and strings of digits (with a sign, single underscores between
    /// digits, surrounding whitespace, and a `.0` tail). Out-of-range values saturate.
    pub fn integer(&mut self, field: &str, default: i64) -> i64 {
        const PLAIN: &str = "Input should be a valid integer";
        const UNPARSABLE: &str =
            "Input should be a valid integer, unable to parse string as an integer";
        let parsed = match self.args.get(field) {
            None => return default,
            Some(Value::Bool(flag)) => Ok(i64::from(*flag)),
            Some(Value::Number(number)) => match (number.as_i64(), number.as_u64()) {
                (Some(value), _) => Ok(value),
                (None, Some(_)) => Ok(i64::MAX),
                (None, None) => {
                    let value = number.as_f64().unwrap_or(f64::NAN);
                    if value.fract() != 0.0 {
                        Err("Input should be a valid integer, got a number with a fractional part")
                    } else if value.abs() > i64::MAX as f64 {
                        Err("Unable to parse input string as an integer, exceeded maximum size")
                    } else {
                        Ok(value as i64)
                    }
                }
            },
            Some(Value::String(text)) => parse_python_int(text).ok_or(UNPARSABLE),
            Some(_) => Err(PLAIN),
        };
        parsed.unwrap_or_else(|message| {
            self.errors.push(format!("{field}: {message}"));
            default
        })
    }

    /// An `int` field constrained to `min..=max`, as pydantic's `Field(ge=, le=)`
    /// reports a value outside it.
    pub fn bounded_integer(&mut self, field: &str, default: i64, min: i64, max: i64) -> i64 {
        let before = self.errors.len();
        let value = self.integer(field, default);
        if self.errors.len() > before {
            return default;
        }
        if value < min {
            self.errors.push(format!(
                "{field}: Input should be greater than or equal to {min}"
            ));
            default
        } else if value > max {
            self.errors.push(format!(
                "{field}: Input should be less than or equal to {max}"
            ));
            default
        } else {
            value
        }
    }

    /// A required `Literal[...]` string field.
    pub fn choice(&mut self, field: &str, choices: &[&str]) -> String {
        match self.args.get(field) {
            Some(Value::String(value)) if choices.contains(&value.as_str()) => value.clone(),
            None => {
                self.errors.push(format!("{field}: Field required"));
                String::new()
            }
            Some(_) => {
                let quoted: Vec<String> =
                    choices.iter().map(|choice| format!("'{choice}'")).collect();
                let listed = match quoted.split_last() {
                    Some((last, rest)) if !rest.is_empty() => {
                        format!("{} or {last}", rest.join(", "))
                    }
                    _ => quoted.concat(),
                };
                self.errors
                    .push(format!("{field}: Input should be {listed}"));
                String::new()
            }
        }
    }

    /// `Err` with every collected error, or `Ok` when all fields were valid.
    pub fn finish(self) -> Result<(), ToolError> {
        if self.errors.is_empty() {
            Ok(())
        } else {
            Err(ToolError::InvalidArguments(self.errors))
        }
    }
}

/// A string pydantic's lax mode accepts as an `int`, saturating out of range.
fn parse_python_int(text: &str) -> Option<i64> {
    let text = text.trim();
    // A whole number written with a zero fraction ("7.0", "7.00") counts.
    let text = match text.split_once('.') {
        Some((whole, zeros)) if !zeros.is_empty() && zeros.bytes().all(|b| b == b'0') => whole,
        Some(_) => return None,
        None => text,
    };
    let (negative, digits) = match text.as_bytes().first() {
        Some(b'-') => (true, &text[1..]),
        Some(b'+') => (false, &text[1..]),
        _ => (false, text),
    };
    // Digits with single underscores between them, as Python's `int()`.
    if digits.is_empty()
        || digits.starts_with('_')
        || digits.ends_with('_')
        || digits.contains("__")
        || !digits.bytes().all(|b| b.is_ascii_digit() || b == b'_')
    {
        return None;
    }
    let mut value: i64 = 0;
    for digit in digits.bytes().filter(u8::is_ascii_digit) {
        value = value
            .saturating_mul(10)
            .saturating_add(i64::from(digit - b'0'));
    }
    Some(if negative {
        value.saturating_neg()
    } else {
        value
    })
}

/// Constraints applied to every tool execution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SandboxPolicy {
    /// The workspace root, fully resolved.
    workspace: PathBuf,
    /// Further roots tools may reach: the skill directories, so a skill's bundled
    /// files can be read. (The jail has no read/write split, as in Python; a write
    /// there still passes the approval gate.)
    allow_paths: Vec<PathBuf>,
    /// Beyond Python: further roots that hold agent86's own files (the user's
    /// `~/.agent86`), for [`SandboxPolicy::guarded`]. They add nothing to the jail.
    guarded_roots: Vec<PathBuf>,
    pub max_output_chars: usize,
    /// How long one sandboxed process may run before its tree is killed.
    pub timeout: Duration,
    /// Extra environment variable names forwarded into tool processes.
    pub env_passthrough: Vec<String>,
    /// Whether network access is allowed (`web_fetch`).
    pub network: bool,
}

impl SandboxPolicy {
    /// A policy jailed to `workspace`, which must exist.
    pub fn new(workspace: &Path) -> std::io::Result<Self> {
        Ok(Self {
            workspace: std::fs::canonicalize(workspace)?,
            allow_paths: Vec::new(),
            guarded_roots: Vec::new(),
            max_output_chars: DEFAULT_MAX_OUTPUT_CHARS,
            timeout: Duration::from_secs(30),
            env_passthrough: Vec::new(),
            network: true,
        })
    }

    pub fn workspace(&self) -> &Path {
        &self.workspace
    }

    /// This policy jailed to `root` instead (a git worktree, beyond Python), with its
    /// guards, timeout, output cap, passthrough, and network kept, the roots it
    /// already allowed, and `keep` (roots inside the old workspace that must stay
    /// reachable at their real path, such as a project's skill directories).
    pub fn rerooted(&self, root: &Path, keep: Vec<PathBuf>) -> std::io::Result<Self> {
        let mut policy = self.clone();
        policy.workspace = std::fs::canonicalize(root)?;
        let allowed = std::mem::take(&mut policy.allow_paths);
        policy.allow(allowed.into_iter().chain(keep));
        Ok(policy)
    }

    /// Let tools also reach `roots` (already resolved), leaving out any inside the
    /// workspace, as Python's `default_policy` does with the skill roots.
    pub fn allow(&mut self, roots: impl IntoIterator<Item = PathBuf>) {
        for root in roots {
            if !root.starts_with(&self.workspace) && !self.allow_paths.contains(&root) {
                self.allow_paths.push(root);
            }
        }
    }

    /// Also count `roots` as agent86's own files for [`SandboxPolicy::guarded`],
    /// resolved as the jail resolves paths, so a workspace inside one (or equal to
    /// it) is covered. The jail itself is unchanged.
    pub fn guard(&mut self, roots: impl IntoIterator<Item = PathBuf>) {
        for root in roots {
            let root = resolve(&root);
            if !self.guarded_roots.contains(&root) {
                self.guarded_roots.push(root);
            }
        }
    }

    /// Beyond Python: whether `target` (as [`SandboxPolicy::resolve_within`] gave it)
    /// is agent86's own configuration or skills: the workspace's `.agent86/` or
    /// `.claude/skills/`, a skill root outside the workspace (such as
    /// `~/.agent86/skills`, which every project loads), or a root given to
    /// [`SandboxPolicy::guard`] (the user's `~/.agent86`, so running in that very
    /// directory still guards its `config.toml`). What is written there runs, or is
    /// read as instructions, from then on.
    ///
    /// Names are compared as Windows and macOS do (ignoring ASCII case, and on
    /// Windows the trailing dots and spaces it drops), so `.AGENT86./` is caught
    /// too; on Linux that only asks about a little more than it must.
    pub fn guarded(&self, target: &Path) -> bool {
        if self
            .allow_paths
            .iter()
            .chain(&self.guarded_roots)
            .any(|root| target.starts_with(root))
        {
            return true;
        }
        let Ok(inside) = target.strip_prefix(&self.workspace) else {
            return false;
        };
        let names: Vec<String> = inside
            .components()
            .take(2)
            .filter_map(|component| match component {
                Component::Normal(name) => Some(
                    name.to_string_lossy()
                        .trim_end_matches(['.', ' '])
                        .to_ascii_lowercase(),
                ),
                _ => None,
            })
            .collect();
        match names.as_slice() {
            [first, ..] if first == ".agent86" => true,
            [first, second] => first == ".claude" && second == "skills",
            _ => false,
        }
    }

    /// Resolve `path` (relative to the workspace) and enforce the jail.
    ///
    /// Resolution follows symlinks the way Python's `Path.resolve()` does, so a
    /// link inside the workspace that points outside it is refused.
    pub fn resolve_within(&self, path: &str) -> Result<PathBuf, ToolError> {
        let candidate = resolve(&self.workspace.join(path));
        let inside = std::iter::once(&self.workspace)
            .chain(&self.allow_paths)
            .any(|root| candidate.starts_with(root));
        if inside {
            Ok(candidate)
        } else {
            Err(ToolError::raised(
                "PolicyError",
                format!(
                    "Path '{path}' resolves outside the workspace jail ({}).",
                    display_path(&self.workspace)
                ),
            ))
        }
    }

    /// The jail root `path` (as [`SandboxPolicy::resolve_within`] gave it) lies
    /// under: the workspace, or the allowed root holding it. The search tools keep
    /// a walk inside the root it started in (beyond Python).
    pub fn root_of(&self, path: &Path) -> Option<&Path> {
        std::iter::once(&self.workspace)
            .chain(&self.allow_paths)
            .find(|root| path.starts_with(root))
            .map(PathBuf::as_path)
    }

    /// Fail unless network access is allowed.
    pub fn require_network(&self) -> Result<(), ToolError> {
        if self.network {
            Ok(())
        } else {
            Err(ToolError::raised(
                "PolicyError",
                "Network access is disabled by the sandbox policy.",
            ))
        }
    }

    /// Cap `text` at the output limit, saying how much was dropped.
    pub fn truncate(&self, text: String) -> String {
        let length = text.chars().count();
        if length <= self.max_output_chars {
            return text;
        }
        let kept: String = text.chars().take(self.max_output_chars).collect();
        format!(
            "{kept}\n... [truncated {} bytes]",
            length - self.max_output_chars
        )
    }
}

/// Make `path` absolute and canonical, like Python's non-strict `Path.resolve()`.
///
/// Each existing prefix is canonicalized (following symlinks) before the next
/// component is applied, so `..` acts on the real location; components past the
/// last existing directory are appended lexically.
///
/// A symlink whose target does not exist (yet) is followed too, as Python's
/// `Path.resolve()` follows it: `canonicalize` fails on it, and keeping the link's
/// own path would let `notes -> ~/.ssh/authorized_keys` pass the jail while a
/// write through it lands outside. Links are followed at most [`MAX_LINKS`] deep,
/// past which the OS refuses the path anyway.
fn resolve(path: &Path) -> PathBuf {
    resolve_following(path, 0)
}

/// How many dangling symlinks [`resolve`] follows in a chain, as Linux's limit.
const MAX_LINKS: usize = 40;

fn resolve_following(path: &Path, links: usize) -> PathBuf {
    let mut resolved = PathBuf::new();
    for component in path.components() {
        match component {
            Component::Prefix(_) | Component::RootDir => resolved.push(component),
            Component::CurDir => {}
            Component::ParentDir => {
                resolved.pop();
            }
            Component::Normal(part) => {
                resolved.push(part);
                if let Ok(real) = std::fs::canonicalize(&resolved) {
                    resolved = real;
                } else if links < MAX_LINKS {
                    if let Ok(target) = std::fs::read_link(&resolved) {
                        let base = resolved.parent().map(Path::to_path_buf).unwrap_or_default();
                        resolved = resolve_following(&base.join(target), links + 1);
                    }
                }
            }
        }
    }
    resolved
}

/// Every string in `value`, however deep, with the user's secrets taken out.
fn redact_value(value: &mut Value, ctx: &ToolContext) {
    match value {
        Value::String(text) => *text = ctx.secrets.redact(text),
        Value::Array(items) => items.iter_mut().for_each(|item| redact_value(item, ctx)),
        Value::Object(map) => map.values_mut().for_each(|item| redact_value(item, ctx)),
        _ => {}
    }
}

/// `path` without Windows' `\\?\` verbatim prefix, for handing to other programs:
/// `cmd.exe` refuses a verbatim working directory and falls back to the Windows
/// directory, so child processes must get the plain form.
pub fn plain_path(path: &Path) -> PathBuf {
    PathBuf::from(display_path(path))
}

/// A path for messages, without Windows' `\\?\` verbatim prefix.
pub fn display_path(path: &Path) -> String {
    let text = path.display().to_string();
    if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
        format!(r"\\{rest}")
    } else if let Some(rest) = text.strip_prefix(r"\\?\") {
        rest.to_owned()
    } else {
        text
    }
}

/// Where the editor driving the agent keeps its files (beyond Python; the ACP
/// server installs it). The file tools read and write text through it when it is
/// set, so they see unsaved buffers and the editor sees what the agent wrote; with
/// none, they use the disk exactly as before. Paths are absolute and inside the
/// workspace: the tools resolve them through the jail first.
pub trait EditorFiles: Send + Sync + std::fmt::Debug {
    /// The editor's text of `path`, or `None` when it has none to give (the editor
    /// does not offer reads, does not know the file, or did not answer): the tool
    /// then reads the disk.
    fn read_text(&self, path: &Path) -> Option<String>;

    /// Write `content` through the editor. `None` means the editor does not offer
    /// writes, so the tool writes the disk; `Some(Err)` is the editor refusing, which
    /// fails the call rather than writing around it.
    fn write_text(&self, path: &Path, content: &str) -> Option<Result<(), String>>;
}

/// Ambient state handed to every tool at execution time.
#[derive(Debug, Clone)]
pub struct ToolContext {
    pub policy: SandboxPolicy,
    /// Where commands and Python snippets run.
    pub executor: Executor,
    /// `web_fetch` settings.
    pub web: web::WebSettings,
    /// Long-term memory for `remember` and `recall`; `None` when memory is off.
    pub memory: Option<crate::session::SessionStore>,
    /// The discovered skills, for `use_skill`.
    pub skills: Arc<crate::skills::Skills>,
    /// The skill `use_skill` activated this turn, whose `allowed-tools` restrict
    /// what may run. Shared by clones of the context.
    active_skill: Arc<std::sync::Mutex<Option<Arc<crate::skills::Skill>>>>,
    /// Secrets the user entered (beyond Python): set in tool processes' environment,
    /// and redacted from every result. Shared by clones and sub-agent forks.
    pub secrets: crate::vault::SecretVault,
    /// The editor's files, when an editor drives the agent. Shared by clones and
    /// sub-agent forks.
    pub editor: Option<Arc<dyn EditorFiles>>,
    /// The specialist sub-agents (beyond Python), for `delegate` and `use_skill`.
    pub specialties: Arc<crate::agents_def::Specialties>,
    /// What narrows this context (beyond Python): the specialty it runs, or one it
    /// was delegated from. Set once when a sub-agent is spawned (or for `run
    /// --agent`), never by the model, and checked with the active skill's list.
    pub scope: Option<Arc<ToolScope>>,
    /// Whether a `use_skill` hand-off to a specialty could be made from here: the
    /// harness delegates, `delegate` is offered at this depth, and this context may
    /// call it. Set by the harness.
    pub can_delegate: bool,
    /// The fan-out this context's sub-agent belongs to (beyond Python): siblings
    /// running at once share its spend and its stop. Inherited by forks, so a
    /// sibling's own delegations stop with it.
    pub fanout: Option<Arc<crate::subagent::FanOut>>,
    /// On a fan-out thread: every sub-agent here calls a provider copy with an
    /// HTTP client of its own ([`crate::provider::Provider::fresh`]).
    pub fresh_clients: bool,
    /// The git worktree this context is jailed to, when a specialty runs isolated;
    /// a delegation from inside asking for isolation is served by the same one.
    pub worktree: Option<Arc<crate::worktree::Worktree>>,
    /// The card a sub-agent's progress is reported on (beyond Python): the
    /// top-level delegation's, which nested runs share.
    pub card: Option<Arc<crate::subagent::Card>>,
    /// The sub-agent run this context belongs to (beyond Python), with its progress,
    /// so a question it asks can say who asks. Set when a sub-agent is spawned.
    pub subagent: Option<Arc<crate::subagent::SubagentRun>>,
    /// The renderer the embedder declared (beyond Python; ADR 0005), for
    /// `render_ui`: its catalogs and the surfaces drawn. Shared by clones;
    /// sub-agent forks have none, since only the main loop draws.
    #[cfg(feature = "agent86ui")]
    pub ui: Option<Arc<crate::agent86ui::UiSession>>,
}

/// What a specialist sub-agent may do (beyond Python): its tools, approval mode,
/// and always-asked tools, already narrowed by whoever delegated to it. Authority
/// only narrows: a nested delegation intersects the lists, keeps the stricter
/// mode, and unites the always-asked tools.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ToolScope {
    /// Who runs under it, for refusals and approval prompts: the specialty's name.
    pub label: String,
    /// Only these tools, when set.
    pub only: Option<Vec<String>>,
    /// Never these (a specialty with no `tools` line inherits all but `delegate`).
    pub except: Vec<String>,
    /// Applies only when stricter than the session's mode.
    pub approval: Option<crate::types::ApprovalMode>,
    /// Asked about in every mode but `deny`.
    pub confirm: Vec<String>,
    /// The skills preloaded into it, so `use_skill` does not hand one back to it.
    pub preloaded: Vec<String>,
    /// Runs in a git worktree: MCP tools, which act outside the jail, are allowed
    /// only when `only` names them.
    pub isolated: bool,
}

impl ToolScope {
    pub fn allows(&self, name: &str) -> bool {
        let named = self
            .only
            .as_ref()
            .is_some_and(|only| only.iter().any(|tool| tool == name));
        if self.isolated && name.starts_with("mcp__") && !named {
            return false;
        }
        (self.only.is_none() || named) && !self.except.iter().any(|tool| tool == name)
    }

    /// This scope narrowed by `outer`, the caller's.
    pub fn within(mut self, outer: Option<&ToolScope>) -> Self {
        let Some(outer) = outer else {
            return self;
        };
        self.only = match (self.only.take(), &outer.only) {
            (Some(mine), Some(theirs)) => Some(
                mine.into_iter()
                    .filter(|tool| theirs.contains(tool))
                    .collect(),
            ),
            (Some(mine), None) => Some(mine),
            (None, theirs) => theirs.clone(),
        };
        for tool in &outer.except {
            if !self.except.contains(tool) {
                self.except.push(tool.clone());
            }
        }
        self.approval = stricter(self.approval, outer.approval);
        self.isolated |= outer.isolated;
        for tool in &outer.confirm {
            if !self.confirm.contains(tool) {
                self.confirm.push(tool.clone());
            }
        }
        self
    }
}

/// The stricter of two modes (`deny`, then `ask`, then `auto`); `None` imposes nothing.
pub fn stricter(
    a: Option<crate::types::ApprovalMode>,
    b: Option<crate::types::ApprovalMode>,
) -> Option<crate::types::ApprovalMode> {
    use crate::types::ApprovalMode::{Ask, Auto, Deny};
    let rank = |mode| match mode {
        Deny => 2,
        Ask => 1,
        Auto => 0,
    };
    match (a, b) {
        (Some(a), Some(b)) => Some(if rank(a) >= rank(b) { a } else { b }),
        (a, None) => a,
        (None, b) => b,
    }
}

impl ToolContext {
    /// A context jailed to `workspace`.
    pub fn new(workspace: &Path) -> std::io::Result<Self> {
        Ok(Self {
            policy: SandboxPolicy::new(workspace)?,
            executor: Executor::Subprocess,
            web: web::WebSettings::default(),
            memory: None,
            skills: Arc::default(),
            active_skill: Arc::default(),
            secrets: crate::vault::SecretVault::default(),
            editor: None,
            specialties: Arc::default(),
            scope: None,
            can_delegate: false,
            fanout: None,
            fresh_clients: false,
            worktree: None,
            card: None,
            subagent: None,
            #[cfg(feature = "agent86ui")]
            ui: None,
        })
    }

    fn active(&self) -> std::sync::MutexGuard<'_, Option<Arc<crate::skills::Skill>>> {
        self.active_skill
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Make `skill` the active one, replacing (never stacking on) any other.
    pub fn activate_skill(&self, skill: &Arc<crate::skills::Skill>) {
        *self.active() = Some(Arc::clone(skill));
    }

    /// Lift the active skill's restriction, as the end of a turn does.
    pub fn clear_skill(&self) {
        *self.active() = None;
    }

    /// A copy for a sub-agent: the same tools and jail, and its own active skill,
    /// starting as this context's, so what it activates restricts only itself.
    /// It draws no UI: only the main loop has the renderer.
    pub fn fork(&self) -> Self {
        let mut forked = self.clone();
        forked.active_skill = Arc::new(std::sync::Mutex::new(self.active_skill()));
        #[cfg(feature = "agent86ui")]
        {
            forked.ui = None;
        }
        forked
    }

    pub fn active_skill(&self) -> Option<Arc<crate::skills::Skill>> {
        self.active().clone()
    }

    /// Whether the specialty this context runs under (if any) permits `name`.
    pub fn scope_allows(&self, name: &str) -> bool {
        self.scope.as_deref().is_none_or(|scope| scope.allows(name))
    }

    /// Whether `name` may be called now, given the active skill's `allowed-tools`.
    /// `use_skill` always may: it is how the model switches skills, and a skill
    /// that forgot to list it would otherwise be a one-way door.
    pub fn allowed_tool(&self, name: &str) -> bool {
        // A specialty's own list is not lifted for `use_skill`: it is set at spawn
        // and the model cannot change it.
        if !self.scope_allows(name) {
            return false;
        }
        match self.active().as_deref() {
            Some(skill) if !skill.allowed_tools.is_empty() => {
                name == "use_skill" || skill.allowed_tools.iter().any(|tool| tool == name)
            }
            _ => true,
        }
    }
}

/// Holds every available tool, exposes their specs, and dispatches calls.
///
/// Cloning shares the same tools: the MCP manager keeps a clone so it can take a
/// dropped server's tools out, and put them back on reconnect, while the agent
/// loop is using the registry, as Python's lock-guarded `ToolRegistry` allows.
#[derive(Default, Clone)]
pub struct ToolRegistry {
    inner: Arc<RwLock<RegistryInner>>,
}

#[derive(Default)]
struct RegistryInner {
    /// In registration order, which is the order specs are advertised in.
    tools: Vec<Arc<dyn Tool>>,
    /// Names dropped by [`ToolRegistry::try_register`] because something already owned them.
    collisions: Vec<String>,
}

impl ToolRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    fn read(&self) -> std::sync::RwLockReadGuard<'_, RegistryInner> {
        self.inner
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    fn write(&self) -> std::sync::RwLockWriteGuard<'_, RegistryInner> {
        self.inner
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    pub fn register(&self, tool: Box<dyn Tool>) -> Result<(), String> {
        let mut inner = self.write();
        if inner.tools.iter().any(|known| known.name() == tool.name()) {
            return Err(format!("Tool '{}' is already registered.", tool.name()));
        }
        inner.tools.push(Arc::from(tool));
        Ok(())
    }

    /// Register `tool` unless its name is taken, recording the clash if it is. The
    /// lenient path for mounting MCP tools, where one collision must not abort the run.
    pub fn try_register(&self, tool: Arc<dyn Tool>) -> bool {
        let mut inner = self.write();
        if inner.tools.iter().any(|known| known.name() == tool.name()) {
            inner.collisions.push(tool.name().to_owned());
            return false;
        }
        inner.tools.push(tool);
        true
    }

    /// Remove `tool` only if it is the object registered under its name, so a dropped
    /// MCP tool that lost a name collision never takes the winner out with it.
    /// Register a shared tool unless its name is taken, without recording a
    /// collision: for a change the user asked for, which reports its own.
    pub fn register_shared(&self, tool: Arc<dyn Tool>) -> bool {
        let mut inner = self.write();
        if inner.tools.iter().any(|known| known.name() == tool.name()) {
            return false;
        }
        inner.tools.push(tool);
        true
    }

    pub fn unregister_tool(&self, tool: &Arc<dyn Tool>) -> bool {
        let mut inner = self.write();
        let before = inner.tools.len();
        inner.tools.retain(|known| !same_tool(known, tool));
        inner.tools.len() != before
    }

    /// Is this exact tool object registered (not merely one with the same name)?
    pub fn contains_tool(&self, tool: &Arc<dyn Tool>) -> bool {
        self.read().tools.iter().any(|known| same_tool(known, tool))
    }

    /// Names [`ToolRegistry::try_register`] refused, in the order they were refused.
    pub fn collisions(&self) -> Vec<String> {
        self.read().collisions.clone()
    }

    pub fn get(&self, name: &str) -> Option<Arc<dyn Tool>> {
        self.read()
            .tools
            .iter()
            .find(|tool| tool.name() == name)
            .cloned()
    }

    /// Tool names, sorted.
    pub fn names(&self) -> Vec<String> {
        let mut names: Vec<String> = self
            .read()
            .tools
            .iter()
            .map(|tool| tool.name().to_owned())
            .collect();
        names.sort_unstable();
        names
    }

    /// Specs in registration order.
    pub fn specs(&self) -> Vec<ToolSpec> {
        let tools: Vec<Arc<dyn Tool>> = self.read().tools.clone();
        tools.iter().map(|tool| tool.spec()).collect()
    }

    /// Run `call`. The lock is released before the tool runs, so a long call never
    /// blocks the MCP manager from updating the registry.
    ///
    /// Every result passes through here, from the loop, its parallel reads, and
    /// sub-agents, so this is where a secret the user entered is taken out of what a
    /// tool returns, before the model, the transcript, or the trace sees it.
    pub fn dispatch(&self, call: &ToolCall, ctx: &ToolContext) -> ToolResult {
        let mut result = self.dispatch_unredacted(call, ctx);
        if !ctx.secrets.is_empty() {
            result.content = ctx.secrets.redact(&result.content);
            result.error = result.error.map(|error| ctx.secrets.redact(&error));
            // The metadata is kept too (the session's steps, the transcript), and a
            // file tool's diff in it comes from the expanded arguments.
            for value in result.metadata.values_mut() {
                redact_value(value, ctx);
            }
        }
        result
    }

    fn dispatch_unredacted(&self, call: &ToolCall, ctx: &ToolContext) -> ToolResult {
        match self.get(&call.name) {
            Some(_) if !ctx.scope_allows(&call.name) => scope_refusal(call, ctx),
            Some(_) if !ctx.allowed_tool(&call.name) => skill_refusal(call, ctx),
            Some(tool) => match with_secrets(tool.as_ref(), call, ctx) {
                Ok(call) => {
                    let (call, repaired) = repaired_call(tool.as_ref(), call);
                    let mut result = tool.run(&call, ctx);
                    if !result.ok {
                        if let Some(hint) = unparsed_json_hint(&tool.parameters(), &call.arguments)
                        {
                            let error = result.error.get_or_insert_with(String::new);
                            error.push('\n');
                            error.push_str(&hint);
                        }
                    }
                    if !repaired.is_empty() {
                        result
                            .metadata
                            .insert(ARGS_REPAIRED_KEY.to_owned(), json!(repaired));
                    }
                    result
                }
                Err(error) => ToolResult {
                    call_id: call.id.clone(),
                    ..failure(&call.name, error)
                },
            },
            None => ToolResult {
                call_id: call.id.clone(),
                ..failure(
                    &call.name,
                    format!(
                        "Unknown tool '{}'. Available: {}.",
                        call.name,
                        self.names().join(", ")
                    ),
                )
            },
        }
    }
}

/// `call` as `tool` runs it: with `${secret:NAME}` in its arguments replaced by the
/// values, for a tool that [`Tool::expands_secrets`], or unchanged. The call the
/// loop keeps (history, trace, approval summary) is never the expanded one.
pub fn with_secrets<'a>(
    tool: &dyn Tool,
    call: &'a ToolCall,
    ctx: &ToolContext,
) -> Result<std::borrow::Cow<'a, ToolCall>, String> {
    if !tool.expands_secrets() {
        return Ok(std::borrow::Cow::Borrowed(call));
    }
    let Value::Object(arguments) = ctx
        .secrets
        .expand_value(&Value::Object(call.arguments.clone()))?
    else {
        unreachable!("an object expands to an object")
    };
    Ok(std::borrow::Cow::Owned(ToolCall {
        arguments,
        ..call.clone()
    }))
}

/// The `ToolResult::metadata` key under which [`ToolRegistry::dispatch`] lists the
/// parameters it repaired, so the loop can record a `tool_args_repaired` event.
pub const ARGS_REPAIRED_KEY: &str = "args_repaired";

/// `call` with its JSON-string arguments repaired against `tool`'s schema, and the
/// names of the parameters repaired. The call the loop keeps is never this one.
fn repaired_call<'a>(
    tool: &dyn Tool,
    call: std::borrow::Cow<'a, ToolCall>,
) -> (std::borrow::Cow<'a, ToolCall>, Vec<String>) {
    let Some((arguments, repaired)) = repair_arguments(&tool.parameters(), &call.arguments) else {
        return (call, Vec::new());
    };
    let call = ToolCall {
        arguments,
        ..call.into_owned()
    };
    (std::borrow::Cow::Owned(call), repaired)
}

/// Beyond Python: models sometimes send an array or an object argument as a JSON
/// string (`"[\"markdown\"]"` where the schema wants `["markdown"]`), which the
/// tool then rejects and the turn loses a step. When a parameter's schema accepts
/// an array or an object but not a string, and the model sent a string that parses
/// as JSON of that kind, the parsed value is used. Anything else is left alone, so
/// the error the model gets for it is unchanged, and a string parameter that
/// happens to hold JSON is never touched.
///
/// `None` when nothing needed repair, else the repaired arguments and the names of
/// the parameters that were.
pub fn repair_arguments(
    schema: &Value,
    arguments: &Map<String, Value>,
) -> Option<(Map<String, Value>, Vec<String>)> {
    let properties = schema.get("properties")?.as_object()?;
    let mut repaired_arguments = arguments.clone();
    let mut repaired = Vec::new();
    for (name, value) in arguments {
        let (Value::String(text), Some(property)) = (value, properties.get(name)) else {
            continue;
        };
        let accepted = accepted_types(property);
        if accepted.contains(&"string") {
            continue;
        }
        let Ok(parsed) = serde_json::from_str::<Value>(text.trim()) else {
            continue;
        };
        let kind = match parsed {
            Value::Array(_) => "array",
            Value::Object(_) => "object",
            _ => continue,
        };
        if accepted.contains(&kind) {
            repaired_arguments.insert(name.clone(), parsed);
            repaired.push(name.clone());
        }
    }
    (!repaired.is_empty()).then_some((repaired_arguments, repaired))
}

/// Beyond Python: what to tell the model when it sent an array or an object
/// argument as a string holding JSON that does not parse, so
/// [`repair_arguments`] could not unwrap it and the tool's own error ("Input
/// should be a valid list") does not say why. Models that make the mistake tend
/// to repeat it; naming where the JSON broke lets them fix it. `None` when no
/// argument looks like that.
pub fn unparsed_json_hint(schema: &Value, arguments: &Map<String, Value>) -> Option<String> {
    let properties = schema.get("properties")?.as_object()?;
    let hints: Vec<String> = arguments
        .iter()
        .filter_map(|(name, value)| {
            let text = value.as_str()?.trim();
            let accepted = accepted_types(properties.get(name)?);
            let wanted = match text.chars().next()? {
                '[' if accepted.contains(&"array") => "array",
                '{' if accepted.contains(&"object") => "object",
                _ => return None,
            };
            if accepted.contains(&"string") {
                return None;
            }
            let error = serde_json::from_str::<Value>(text).err()?;
            Some(format!(
                "'{name}' was sent as a string holding JSON that does not parse ({error}). \
                 Send it as a JSON {wanted} itself, not inside a string, and check that \
                 every bracket and brace closes in order."
            ))
        })
        .collect();
    (!hints.is_empty()).then(|| hints.join("\n"))
}

/// The JSON types a property schema accepts: its `type` (a name or a list), and
/// those of its `anyOf`/`oneOf` branches (pydantic writes `Optional[list]` that way).
fn accepted_types(property: &Value) -> Vec<&str> {
    let mut types = Vec::new();
    match property.get("type") {
        Some(Value::String(kind)) => types.push(kind.as_str()),
        Some(Value::Array(kinds)) => types.extend(kinds.iter().filter_map(Value::as_str)),
        _ => {}
    }
    for key in ["anyOf", "oneOf"] {
        if let Some(branches) = property.get(key).and_then(Value::as_array) {
            for branch in branches {
                types.extend(accepted_types(branch));
            }
        }
    }
    types
}

/// The answer to a call outside the running specialty's tools, naming what it
/// may use so the model can re-plan.
pub fn scope_refusal(call: &ToolCall, ctx: &ToolContext) -> ToolResult {
    let label = ctx
        .scope
        .as_deref()
        .map_or("", |scope| scope.label.as_str());
    ToolResult {
        call_id: call.id.clone(),
        ..failure(
            &call.name,
            format!(
                "Tool '{}' is not permitted for the '{label}' sub-agent. Use only the tools you \
                 were given.",
                call.name
            ),
        )
    }
}

/// The answer to a call the active skill's `allowed-tools` forbid, naming the
/// skill and its list so the model can re-plan rather than retry.
fn skill_refusal(call: &ToolCall, ctx: &ToolContext) -> ToolResult {
    let skill = ctx.active_skill();
    let (name, allowed) = skill
        .as_deref()
        .map(|skill| (skill.name.as_str(), skill.allowed_tools.join(", ")))
        .unwrap_or_default();
    ToolResult {
        call_id: call.id.clone(),
        ..failure(
            &call.name,
            format!(
                "Tool '{}' is not permitted while the skill '{name}' is active. That skill's \
                 allowed-tools are: {allowed}. Use one of those, or finish with the skill first.",
                call.name
            ),
        )
    }
}

fn same_tool(a: &Arc<dyn Tool>, b: &Arc<dyn Tool>) -> bool {
    std::ptr::eq(Arc::as_ptr(a).cast::<()>(), Arc::as_ptr(b).cast::<()>())
}

/// Python's built-in tools, then, beyond Python, the read-only search tools
/// (`search_files`, `find_files`), then `remember` and `recall` when memory is on,
/// `use_skill` when a skill was found, and `delegate` when `[agents]` is on, in
/// Python's registration order (`default_registry`). Last, beyond Python,
/// `request_secret` when someone is there to answer it (`with_secrets`).
pub fn default_registry(
    with_memory: bool,
    with_skills: bool,
    with_delegate: bool,
    with_secrets: bool,
) -> ToolRegistry {
    let registry = builtin_registry();
    for tool in [
        Box::new(search::SearchFilesTool) as Box<dyn Tool>,
        Box::new(search::FindFilesTool),
    ] {
        registry
            .register(tool)
            .expect("search tool names are unique");
    }
    if with_memory {
        for tool in [
            Box::new(memory::RememberTool) as Box<dyn Tool>,
            Box::new(memory::RecallTool),
        ] {
            registry
                .register(tool)
                .expect("memory tool names are unique");
        }
    }
    if with_skills {
        registry
            .register(Box::new(skills::UseSkillTool))
            .expect("use_skill is unique");
    }
    if with_delegate {
        registry
            .register(Box::new(delegate::DelegateTool))
            .expect("delegate is unique");
    }
    if with_secrets {
        registry
            .register(Box::new(secret::RequestSecretTool))
            .expect("request_secret is unique");
    }
    registry
}

/// Python's built-in tools, in its registration order.
pub fn builtin_registry() -> ToolRegistry {
    let registry = ToolRegistry::new();
    for tool in [
        Box::new(files::ReadFileTool) as Box<dyn Tool>,
        Box::new(files::WriteFileTool),
        Box::new(files::EditFileTool),
        Box::new(files::ListDirTool),
        Box::new(exec::RunCommandTool),
        Box::new(exec::PythonExecTool),
        Box::new(web::WebFetchTool),
    ] {
        registry
            .register(tool)
            .expect("built-in tool names are unique");
    }
    registry
}