strands-harness 0.1.0

A preconfigured Strands agent in one call
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
//! `create_harness` end to end, including memory and the generalist subagent's memory.
//!
//! These assert the [`AgentConfig`] and model plan [`assemble`] resolves (plugins, interventions,
//! the Background Tasks policy, the model config), and build the agent where its behaviour is
//! observable.

use std::sync::Arc;

use serde_json::json;
use strands::context_manager::ContextManagerStrategy;
use strands::memory::{MemoryEntry, MemoryManagerConfig, SearchOptions};
use strands::models::routing::{ModelRouter, ModelRouterOptions, RoutingCandidate};
use strands::models::{BaseModelConfig, Model};
use strands::sandbox::{ExecuteOptions, ExecutionStream, FileInfo};
use strands::storage::InMemoryStorage;
use strands::testing::{MockModel, MockTurn};
use strands::tools::FunctionTool;
use strands::types::{ContentBlock, ToolUseBlock};
use strands::{InvokeLimits, InvokeOptions, async_trait};

use super::*;
use crate::builtin_tools::{child_options, delegable, subagent_tool_options};
use crate::factory::ChildSpec;
use crate::prompt::HARNESS_CONTRACT;
use crate::test_support::{offline_env, record_logs};
use crate::types::ShellConfig;
use crate::{BuiltinToolName, InterventionValue};

fn mock_model() -> ModelSource {
    MockModel::new().into()
}

/// Options that keep a test off the working directory's `.agent` folder.
fn quiet() -> HarnessAgentOptions {
    HarnessAgentOptions {
        session: Some(SessionOption::Off),
        memory: Some(MemoryOption::Off),
        skills: Some(SkillsOption::Off),
        printer: Some(false),
        ..Default::default()
    }
}

fn quiet_with_mock() -> HarnessAgentOptions {
    HarnessAgentOptions {
        model: Some(mock_model()),
        ..quiet()
    }
}

async fn assembled(options: HarnessAgentOptions) -> Assembly {
    assemble(options, &offline_env()).await.unwrap()
}

async fn rejection(options: HarnessAgentOptions) -> String {
    match assemble(options, &offline_env()).await {
        Ok(_) => panic!("expected an error"),
        Err(error) => error.to_string(),
    }
}

/// The names of the tools the agent config registers, plugin-vended tools included.
fn tool_names(config: &AgentConfig) -> Vec<String> {
    let plugin_tools = config.plugins.iter().flat_map(|plugin| plugin.get_tools());
    config
        .tools
        .iter()
        .cloned()
        .chain(plugin_tools)
        .filter_map(|source| match source {
            ToolSource::Tool(tool) => Some(tool.name().to_owned()),
            _ => None,
        })
        .collect()
}

#[cfg(feature = "bedrock")]
fn plugin_names(config: &AgentConfig) -> Vec<&str> {
    config.plugins.iter().map(|plugin| plugin.name()).collect()
}

fn tool(name: &str, description: &str) -> Arc<dyn Tool> {
    Arc::new(FunctionTool::builder(name, description).callback(|input, _| async move { Ok(input) }))
}

fn sample_tool() -> Arc<dyn Tool> {
    tool("sample_tool", "A sample tool.")
}

fn background(config: &AgentConfig) -> Option<BackgroundTasksConfig> {
    match config.background_tasks.clone()? {
        Toggle::On(config) => Some(config),
        _ => None,
    }
}

fn strings(values: &[&str]) -> Option<Vec<String>> {
    Some(values.iter().map(|value| (*value).to_owned()).collect())
}

fn write_skill(dir: &Path, name: &str) {
    let skill = dir.join(name);
    std::fs::create_dir_all(&skill).unwrap();
    std::fs::write(
        skill.join("SKILL.md"),
        format!("---\nname: {name}\ndescription: A {name} skill.\n---\nDo the {name} thing.\n"),
    )
    .unwrap();
}

fn mock_with_id(model_id: &str) -> Arc<dyn Model> {
    let model = MockModel::new();
    model
        .update_config(BaseModelConfig {
            model_id: Some(model_id.to_owned()),
            ..Default::default()
        })
        .unwrap();
    Arc::new(model)
}

struct Recall;

#[async_trait]
impl strands::memory::MemoryStore for Recall {
    fn name(&self) -> &str {
        "custom"
    }

    fn writable(&self) -> bool {
        false
    }

    async fn search(&self, _query: &str, _options: SearchOptions) -> strands::Result<Vec<MemoryEntry>> {
        Ok(Vec::new())
    }
}

fn custom_manager() -> MemoryManager {
    MemoryManager::new(MemoryManagerConfig {
        stores: vec![Arc::new(Recall)],
        ..Default::default()
    })
    .unwrap()
}

#[cfg(feature = "bedrock")]
#[tokio::test]
async fn builds_an_agent_with_the_default_configuration() {
    let sessions = tempfile::tempdir().unwrap();
    let memory = tempfile::tempdir().unwrap();
    let options = HarnessAgentOptions {
        session: Some(SessionConfig::builder().dir(sessions.path()).build().into()),
        memory: Some(MemoryConfig::builder().dir(memory.path()).build().into()),
        printer: Some(false),
        ..Default::default()
    };
    let assembly = assembled(options).await;
    let names = tool_names(&assembly.config);
    for name in [
        "shell",
        "read",
        "write",
        "edit",
        "web_fetch",
        "subagent",
        "programmatic_tool_caller",
    ] {
        assert!(names.contains(&name.to_owned()), "{name}");
    }
    assert_eq!(assembly.config.system_prompt, Some(HARNESS_CONTRACT.into()));
    assert!(matches!(
        assembly.config.context_manager,
        Some(ContextManagerStrategy::Auto)
    ));
    assert_eq!(
        assembly.model_plan.unwrap().model_id,
        "global.anthropic.claude-opus-5-5"
    );
    assert_eq!(plugin_names(&assembly.config), ["strands:environment"]);
    Agent::new(assembly.config).unwrap();
}

#[tokio::test]
async fn attaches_a_model_router_through_the_model_parameter() {
    let candidates: Vec<RoutingCandidate> = vec![mock_with_id("fast").into(), mock_with_id("deep").into()];
    let router = ModelRouter::new(candidates, ModelRouterOptions::default()).unwrap();
    let options = HarnessAgentOptions {
        model: Some(router.clone().into()),
        ..quiet()
    };
    let agent = create_harness_boxed(options, offline_env()).await.unwrap();
    assert!(Arc::ptr_eq(agent.model(), &router.default_model()));
}

async fn built_tool_names(options: HarnessAgentOptions) -> Vec<String> {
    let mut agent = create_harness_boxed(options, offline_env()).await.unwrap();
    agent.initialize().await.unwrap();
    agent.tools().iter().map(|tool| tool.name().to_owned()).collect()
}

#[tokio::test]
async fn backgrounds_the_subagent_and_leaves_other_compatible_tools_agent_selectable() {
    let policy = background(&assembled(quiet_with_mock()).await.config).unwrap();
    assert_eq!(policy.agentic, strings(&["*"]));
    assert_eq!(policy.always, strings(&["subagent"]));
    assert_eq!(policy.never, None);
    assert!(
        built_tool_names(quiet_with_mock())
            .await
            .contains(&"manage_background_task".to_owned())
    );
}

#[tokio::test]
async fn uses_the_harness_management_tool_name_when_the_policy_names_none() {
    let options = HarnessAgentOptions {
        background_tasks: Some(Toggle::On(BackgroundTasksConfig {
            manage_tool_name: None,
            ..Default::default()
        })),
        ..quiet_with_mock()
    };
    assert!(
        built_tool_names(options)
            .await
            .contains(&"manage_background_task".to_owned())
    );
}

#[tokio::test]
async fn treats_background_tasks_true_the_same_as_the_default() {
    let options = HarnessAgentOptions {
        background_tasks: Some(true.into()),
        ..quiet_with_mock()
    };
    let policy = background(&assembled(options).await.config).unwrap();
    assert_eq!(policy.agentic, strings(&["*"]));
    assert_eq!(policy.always, strings(&["subagent"]));
}

#[tokio::test]
async fn keeps_the_subagent_backgrounded_under_a_custom_policy() {
    let custom = BackgroundTasksConfig {
        manage_tool_name: Some("task_admin".to_owned()),
        always: strings(&["sample_tool", "subagent"]),
        never: strings(&["*", "subagent"]),
        wait_for_completion: Some(false),
        ..Default::default()
    };
    let options = || HarnessAgentOptions {
        background_tasks: Some(Toggle::On(custom.clone())),
        ..quiet_with_mock()
    };
    assert!(built_tool_names(options()).await.contains(&"task_admin".to_owned()));
    let policy = background(&assembled(options()).await.config).unwrap();
    assert_eq!(policy.always, strings(&["sample_tool", "subagent"]));
    assert_eq!(policy.never, strings(&["*"]));
    assert_eq!(policy.agentic, None);
    assert_eq!(policy.wait_for_completion, Some(false));
}

#[tokio::test]
async fn disables_background_tasks_when_requested() {
    let options = HarnessAgentOptions {
        background_tasks: Some(false.into()),
        ..quiet_with_mock()
    };
    assert!(matches!(
        assembled(options).await.config.background_tasks,
        Some(Toggle::Off)
    ));
}

#[tokio::test]
async fn appends_instructions_after_the_contract() {
    let options = HarnessAgentOptions {
        instructions: Some("You are a migration assistant.".to_owned()),
        ..quiet_with_mock()
    };
    let config = assembled(options).await.config;
    let prompt = config.system_prompt.unwrap();
    let text = serde_json::to_value(&prompt).unwrap();
    let text = text.as_str().unwrap();
    assert!(text.starts_with(HARNESS_CONTRACT));
    assert!(text.ends_with("You are a migration assistant."));
}

#[tokio::test]
async fn lets_an_explicit_system_prompt_win_over_instructions() {
    let options = HarnessAgentOptions {
        instructions: Some("ignored".to_owned()),
        system_prompt: Some("my own prompt".into()),
        ..quiet_with_mock()
    };
    assert_eq!(
        assembled(options).await.config.system_prompt,
        Some("my own prompt".into())
    );
}

#[tokio::test]
async fn adds_consumer_tools_alongside_the_built_ins() {
    let options = HarnessAgentOptions {
        tools: vec![sample_tool().into()],
        ..quiet_with_mock()
    };
    let names = tool_names(&assembled(options).await.config);
    for name in ["shell", "read", "sample_tool"] {
        assert!(names.contains(&name.to_owned()), "{name}");
    }
}

#[tokio::test]
async fn enables_the_subagent_delegation_tool_by_default() {
    assert!(tool_names(&assembled(quiet_with_mock()).await.config).contains(&"subagent".to_owned()));
}

#[tokio::test]
async fn disables_the_subagent_tool_when_dropped_from_builtin_tools() {
    let options = HarnessAgentOptions {
        builtin_tools: Some([BuiltinToolName::Read].into()),
        ..quiet_with_mock()
    };
    let names = tool_names(&assembled(options).await.config);
    assert!(!names.contains(&"subagent".to_owned()));
    assert!(names.contains(&"read".to_owned()));
    assert!(!names.contains(&"shell".to_owned()));
}

#[tokio::test]
async fn edits_the_defaults_with_a_builtin_tools_mapping() {
    let options = HarnessAgentOptions {
        builtin_tools: Some(BuiltinToolsConfig::builder().subagent(false).build().into()),
        ..quiet_with_mock()
    };
    let names = tool_names(&assembled(options).await.config);
    assert!(!names.contains(&"subagent".to_owned()));
    for name in ["shell", "read", "write", "edit", "web_fetch"] {
        assert!(names.contains(&name.to_owned()), "{name}");
    }
}

#[tokio::test]
async fn starts_from_nothing_when_the_builtin_tools_mapping_sets_star_to_false() {
    let mapping = BuiltinToolsConfig::builder()
        .all(false)
        .read(true)
        .web_fetch(crate::WebFetchConfig::default())
        .build();
    let options = HarnessAgentOptions {
        builtin_tools: Some(mapping.into()),
        ..quiet_with_mock()
    };
    let mut names = tool_names(&assembled(options).await.config);
    names.sort();
    assert_eq!(names, ["read", "web_fetch"]);
}

#[tokio::test]
async fn configures_the_shell_tool_description() {
    let shell = ShellConfig::builder()
        .description("Run a command in the sandbox.")
        .build();
    let options = HarnessAgentOptions {
        builtin_tools: Some(BuiltinToolsConfig::builder().shell(shell).build().into()),
        ..quiet_with_mock()
    };
    let config = assembled(options).await.config;
    let shell = config
        .tools
        .iter()
        .find_map(|source| match source {
            ToolSource::Tool(tool) if tool.name() == "shell" => Some(tool.description().to_owned()),
            _ => None,
        })
        .unwrap();
    assert_eq!(shell, "Run a command in the sandbox.");
}

struct VendingSandbox;

#[async_trait]
impl strands::sandbox::Sandbox for VendingSandbox {
    fn execute_streaming(&self, _command: &str, _options: ExecuteOptions) -> ExecutionStream {
        Box::pin(futures::stream::empty())
    }

    fn execute_code_streaming(&self, _code: &str, _language: &str, _options: ExecuteOptions) -> ExecutionStream {
        Box::pin(futures::stream::empty())
    }

    async fn read_file(&self, path: &str) -> strands::Result<Vec<u8>> {
        Err(strands::SandboxPathNotFoundError::new(path).into())
    }

    async fn write_file(&self, _path: &str, _content: &[u8]) -> strands::Result<()> {
        Ok(())
    }

    async fn remove_file(&self, _path: &str) -> strands::Result<()> {
        Ok(())
    }

    async fn list_files(&self, _path: &str) -> strands::Result<Vec<FileInfo>> {
        Ok(Vec::new())
    }

    fn get_tools(&self) -> Vec<Arc<dyn Tool>> {
        vec![
            tool("sandbox_bash", "Run bash."),
            tool("sandbox_file_editor", "Edit files."),
            tool("shell", "The sandbox's own shell."),
        ]
    }
}

#[tokio::test]
async fn drops_sandbox_vended_tools() {
    let options = HarnessAgentOptions {
        sandbox: Some(Arc::new(VendingSandbox)),
        ..quiet_with_mock()
    };
    let mut agent = create_harness_boxed(options, offline_env()).await.unwrap();
    agent.initialize().await.unwrap();
    let names: Vec<String> = agent.tools().iter().map(|tool| tool.name().to_owned()).collect();
    for name in ["shell", "read", "write", "edit"] {
        assert!(names.contains(&name.to_owned()), "{name}");
    }
    assert!(!names.contains(&"sandbox_bash".to_owned()));
    assert!(!names.contains(&"sandbox_file_editor".to_owned()));
    let shell = agent.tool_registry().get("shell").unwrap();
    assert_ne!(shell.description(), "The sandbox's own shell.");
}

#[tokio::test]
async fn disables_built_in_tools_with_an_empty_list() {
    let options = HarnessAgentOptions {
        builtin_tools: Some(BuiltinToolsOption::List(Vec::new())),
        tools: vec![sample_tool().into()],
        ..quiet_with_mock()
    };
    let names = tool_names(&assembled(options).await.config);
    assert!(!names.contains(&"shell".to_owned()));
    assert!(!names.contains(&"read".to_owned()));
    assert!(names.contains(&"sample_tool".to_owned()));
}

#[cfg(feature = "openai")]
#[tokio::test]
async fn does_not_register_web_search_as_a_tool() {
    let options = HarnessAgentOptions {
        model: Some("openai/gpt-5.6-sol".into()),
        ..quiet()
    };
    let assembly = assembled(options).await;
    assert!(!tool_names(&assembly.config).contains(&"web_search".to_owned()));
    assert_eq!(
        assembly.model_plan.unwrap().params.unwrap()["tools"],
        json!([{ "type": "web_search" }])
    );
}

#[cfg(feature = "bedrock")]
#[tokio::test]
async fn serves_web_search_on_bedrock_from_the_agentcore_tool_by_default_and_when_named() {
    let assembly = assembled(quiet()).await;
    assert!(tool_names(&assembly.config).contains(&"web_search".to_owned()));
    let named = HarnessAgentOptions {
        model: Some("bedrock/us.amazon.nova-2-lite-v1:0".into()),
        builtin_tools: Some([BuiltinToolName::Read, BuiltinToolName::WebSearch].into()),
        ..quiet()
    };
    assert!(tool_names(&assembled(named).await.config).contains(&"web_search".to_owned()));
}

#[tokio::test]
async fn names_a_model_router_when_it_cannot_serve_web_search() {
    let (logs, _guard) = record_logs();
    let model: Arc<dyn Model> = Arc::new(MockModel::new());
    let router = ModelRouter::new([RoutingCandidate::from(model)], ModelRouterOptions::default()).unwrap();
    let options = HarnessAgentOptions {
        model: Some(ModelSource::Router(router)),
        ..quiet()
    };
    assert!(!tool_names(&assembled(options).await.config).contains(&"web_search".to_owned()));
    assert!(
        logs.lines("INFO")
            .iter()
            .any(|line| line.contains("A pre-built ModelRouter has no built-in web search"))
    );
}

#[cfg(feature = "bedrock")]
#[tokio::test]
async fn collides_with_a_passed_web_search_tool_on_bedrock_like_any_built_in() {
    let mine = tool("web_search", "Search.");
    let options = HarnessAgentOptions {
        tools: vec![Arc::clone(&mine).into()],
        ..quiet()
    };
    assert!(rejection(options).await.contains("registered more than once"));
    let off = HarnessAgentOptions {
        tools: vec![Arc::clone(&mine).into()],
        builtin_tools: Some(BuiltinToolsConfig::builder().web_search(false).build().into()),
        ..quiet()
    };
    let assembly = assembled(off).await;
    assert_eq!(
        tool_names(&assembly.config)
            .iter()
            .filter(|name| *name == "web_search")
            .count(),
        1
    );
}

#[tokio::test]
async fn logs_info_not_a_warning_and_builds_when_default_web_search_hits_a_model_without_search() {
    let (logs, _guard) = record_logs();
    let assembly = assembled(quiet_with_mock()).await;
    assert!(!tool_names(&assembly.config).contains(&"web_search".to_owned()));
    assert!(
        logs.lines("INFO")
            .iter()
            .any(|line| line.contains("has no built-in web search"))
    );
    assert!(
        !logs
            .lines("WARN")
            .iter()
            .any(|line| line.contains("has no built-in web search"))
    );
}

#[tokio::test]
async fn throws_when_web_search_is_explicitly_selected_on_an_unsupported_provider() {
    let list = HarnessAgentOptions {
        model: Some("ollama/llama3".into()),
        builtin_tools: Some([BuiltinToolName::Read, BuiltinToolName::WebSearch].into()),
        ..quiet()
    };
    assert!(rejection(list).await.contains("has no built-in web search"));
    let mapping = HarnessAgentOptions {
        builtin_tools: Some(BuiltinToolsConfig::builder().web_search(true).build().into()),
        ..quiet_with_mock()
    };
    assert!(rejection(mapping).await.contains("has no built-in web search"));
}

#[cfg(feature = "mcp")]
#[tokio::test]
async fn builds_the_exa_tool_for_the_fallback_and_warns_about_the_third_party() {
    let (logs, _guard) = record_logs();
    let options = HarnessAgentOptions {
        builtin_tools: Some(
            BuiltinToolsConfig::builder()
                .web_search(crate::WebSearchSetting::Exa)
                .build()
                .into(),
        ),
        ..quiet_with_mock()
    };
    assert!(tool_names(&assembled(options).await.config).contains(&"web_search".to_owned()));
    assert!(
        logs.lines("WARN")
            .iter()
            .any(|line| line.contains("Exa (exa.ai), a third-party service"))
    );
    assert!(!logs.text().contains("has no built-in web search"));
}

#[cfg(feature = "openai")]
#[tokio::test]
async fn lets_an_explicit_exa_selection_win_over_native_search() {
    let options = HarnessAgentOptions {
        model: Some("openai/gpt-5.6-sol".into()),
        builtin_tools: Some(
            BuiltinToolsConfig::builder()
                .web_search(crate::WebSearchSetting::Exa)
                .build()
                .into(),
        ),
        ..quiet()
    };
    let assembly = assembled(options).await;
    assert!(tool_names(&assembly.config).contains(&"web_search".to_owned()));
    assert!(assembly.model_plan.unwrap().params.unwrap().get("tools").is_none());
}

#[cfg(feature = "mcp")]
#[tokio::test]
async fn serves_the_exa_fallback_on_a_model_instance() {
    let options = HarnessAgentOptions {
        builtin_tools: Some(
            BuiltinToolsConfig::builder()
                .web_search(crate::WebSearchSetting::Exa)
                .build()
                .into(),
        ),
        ..quiet_with_mock()
    };
    assert!(tool_names(&assembled(options).await.config).contains(&"web_search".to_owned()));
}

#[cfg(feature = "anthropic")]
#[tokio::test]
async fn enables_anthropic_native_web_search_from_the_default_set() {
    let options = HarnessAgentOptions {
        model: Some("anthropic/claude-opus-4-8".into()),
        ..quiet()
    };
    let assembly = assembled(options).await;
    assert!(!tool_names(&assembly.config).contains(&"web_search".to_owned()));
    assert_eq!(
        assembly.model_plan.unwrap().anthropic_tools,
        Some(vec![
            json!({ "type": "web_search_20260318", "name": "web_search", "allowed_callers": ["direct"] })
        ])
    );
}

#[cfg(feature = "mantle")]
#[tokio::test]
async fn uses_bedrock_web_search_on_gpt_5_gpt_6_mantle_models_and_agentcore_on_other_mantle_models() {
    let luna = HarnessAgentOptions {
        model: Some("bedrock-mantle/openai.gpt-5.6-luna".into()),
        ..quiet()
    };
    let assembly = assembled(luna).await;
    assert!(!tool_names(&assembly.config).contains(&"web_search".to_owned()));
    assert_eq!(
        assembly.model_plan.unwrap().params.unwrap()["tools"],
        json!([{ "type": "web_search", "external_web_access": true }])
    );
    let oss = HarnessAgentOptions {
        model: Some("bedrock-mantle/openai.gpt-oss-120b-1:0".into()),
        ..quiet()
    };
    let assembly = assembled(oss).await;
    assert!(tool_names(&assembly.config).contains(&"web_search".to_owned()));
    assert!(assembly.model_plan.unwrap().params.unwrap().get("tools").is_none());
}

#[tokio::test]
async fn enables_caching_by_default_on_bedrock_and_anthropic_direct() {
    for model in ["bedrock/global.anthropic.claude-opus-5", "anthropic/claude-opus-4-8"] {
        let options = HarnessAgentOptions {
            model: Some(model.into()),
            ..quiet()
        };
        let plan = assemble(options, &offline_env())
            .await
            .map(|assembly| assembly.model_plan);
        match plan {
            Ok(plan) => assert!(plan.unwrap().caching, "{model}"),
            Err(error) => assert!(
                error.to_string().contains("requires the strands-harness feature"),
                "{error}"
            ),
        }
    }
}

#[cfg(feature = "mantle")]
#[tokio::test]
async fn configures_openai_and_mantle_caching() {
    for model in ["openai/gpt-5.6-sol", "bedrock-mantle/openai.gpt-6-luna"] {
        for caching in [None, Some(true), Some(false)] {
            let options = HarnessAgentOptions {
                model: Some(model.into()),
                caching,
                builtin_tools: Some(BuiltinToolsOption::List(Vec::new())),
                ..quiet()
            };
            let plan = assembled(options).await.model_plan.unwrap();
            assert_eq!(plan.caching, caching != Some(false), "{model} {caching:?}");
        }
    }
}

#[tokio::test]
async fn builds_silently_with_default_caching_on_a_model_instance() {
    let (logs, _guard) = record_logs();
    assembled(quiet_with_mock()).await;
    assert!(!logs.text().contains("prompt caching not applied"));
}

#[tokio::test]
async fn warns_when_caching_is_explicitly_requested_on_a_model_instance() {
    let (logs, _guard) = record_logs();
    let options = HarnessAgentOptions {
        caching: Some(true),
        ..quiet_with_mock()
    };
    assembled(options).await;
    assert!(
        logs.lines("WARN")
            .iter()
            .any(|line| line.contains("pre-built Model instance"))
    );
}

#[cfg(feature = "openai")]
#[tokio::test]
async fn leaves_no_cache_config_when_caching_is_disabled() {
    let options = HarnessAgentOptions {
        model: Some("openai/gpt-5.6-sol".into()),
        caching: Some(false),
        ..quiet()
    };
    assert!(!assembled(options).await.model_plan.unwrap().caching);
}

#[tokio::test]
async fn disables_context_management_when_falsy() {
    let options = HarnessAgentOptions {
        context_manager: Some(ContextManagerStrategy::Disabled),
        ..quiet_with_mock()
    };
    assert!(matches!(
        assembled(options).await.config.context_manager,
        Some(ContextManagerStrategy::Disabled)
    ));
}

#[tokio::test]
async fn uses_the_default_strategy_when_context_manager_is_auto() {
    let options = HarnessAgentOptions {
        context_manager: Some(ContextManagerStrategy::Auto),
        ..quiet_with_mock()
    };
    assert!(matches!(
        assembled(options).await.config.context_manager,
        Some(ContextManagerStrategy::Auto)
    ));
}

#[tokio::test]
async fn lets_an_explicit_context_manager_win() {
    let options = HarnessAgentOptions {
        context_manager: Some(ContextManagerStrategy::Agentic),
        ..quiet_with_mock()
    };
    assert!(matches!(
        assembled(options).await.config.context_manager,
        Some(ContextManagerStrategy::Agentic)
    ));
}

#[tokio::test]
async fn uses_the_default_level_when_effort_is_auto_and_sends_none_when_off() {
    let auto = HarnessAgentOptions {
        model: Some("bedrock/global.anthropic.claude-opus-5".into()),
        ..quiet()
    };
    let Ok(assembly) = assemble(auto, &offline_env()).await else {
        return;
    };
    let fields = assembly.model_plan.unwrap().params.unwrap();
    assert_eq!(fields["output_config"]["effort"], json!("high"));
    let off = HarnessAgentOptions {
        model: Some("bedrock/global.anthropic.claude-opus-5".into()),
        effort: Effort::Off,
        ..quiet()
    };
    assert_eq!(assembled(off).await.model_plan.unwrap().params, None);
}

fn session_id(config: &AgentConfig) -> String {
    config.session_manager.as_ref().unwrap().session_id().to_owned()
}

fn with_session(session: impl Into<SessionOption>) -> HarnessAgentOptions {
    HarnessAgentOptions {
        session: Some(session.into()),
        ..quiet_with_mock()
    }
}

#[tokio::test]
async fn wires_a_session_manager_on_by_default_with_a_random_id() {
    let dir = tempfile::tempdir().unwrap();
    let options = HarnessAgentOptions {
        session: None,
        ..with_session(SessionConfig::builder().dir(dir.path()).build())
    };
    let options = HarnessAgentOptions {
        session: Some(SessionConfig::builder().dir(dir.path()).build().into()),
        ..options
    };
    let id = session_id(&assembled(options).await.config);
    assert_eq!(id.len(), 8);
    assert!(id.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()));
}

#[tokio::test]
async fn mints_distinct_ids_for_two_default_agents() {
    let dir = tempfile::tempdir().unwrap();
    let first = assembled(with_session(SessionConfig::builder().dir(dir.path()).build())).await;
    let second = assembled(with_session(SessionConfig::builder().dir(dir.path()).build())).await;
    assert_ne!(session_id(&first.config), session_id(&second.config));
    let agent = Agent::new(first.config).unwrap();
    assert_eq!(agent.session_id().len(), 8);
}

#[tokio::test]
async fn builds_no_session_manager_when_the_session_is_disabled() {
    assert!(assembled(with_session(false)).await.config.session_manager.is_none());
}

#[tokio::test]
async fn passes_a_session_manager_instance_given_as_session_straight_through() {
    let supplied = SessionManager::new(SessionManagerConfig {
        session_id: Some("mine".to_owned()),
        storage: Some(Arc::new(InMemoryStorage::new())),
        ..Default::default()
    })
    .unwrap();
    let config = assembled(with_session(supplied)).await.config;
    assert_eq!(session_id(&config), "mine");
    assert!(config.storage.is_none());
}

#[tokio::test]
async fn prefers_an_explicitly_supplied_session_manager() {
    let supplied = SessionManager::new(SessionManagerConfig {
        session_id: Some("mine".to_owned()),
        storage: Some(Arc::new(InMemoryStorage::new())),
        ..Default::default()
    })
    .unwrap();
    let options = HarnessAgentOptions {
        session_manager: Some(supplied),
        ..with_session(SessionConfig::builder().id("ignored").build())
    };
    let config = assembled(options).await.config;
    assert_eq!(session_id(&config), "mine");
    assert!(config.storage.is_none());
}

#[tokio::test]
async fn wires_a_session_manager_when_a_session_id_is_given() {
    let dir = tempfile::tempdir().unwrap();
    let config = assembled(with_session(
        SessionConfig::builder().id("user-42").dir(dir.path()).build(),
    ))
    .await
    .config;
    assert_eq!(session_id(&config), "user-42");
}

#[tokio::test]
async fn persists_messages_before_the_invocation_finishes() {
    let dir = tempfile::tempdir().unwrap();
    let model = MockModel::new().with_turn(MockTurn::error(|| {
        strands::Error::other("Stop before calling the model")
    }));
    let options = HarnessAgentOptions {
        model: Some(model.into()),
        session: Some(SessionConfig::builder().id("checkpoint").dir(dir.path()).build().into()),
        builtin_tools: Some(BuiltinToolsOption::List(Vec::new())),
        builtin_plugins: Some(Vec::new()),
        context_manager: Some(ContextManagerStrategy::Disabled),
        retry_strategy: Some(Vec::new()),
        ..quiet()
    };
    let mut agent = create_harness_boxed(options, offline_env()).await.unwrap();
    let error = agent.invoke("Remember the checkpoint").await.unwrap_err();
    assert!(error.to_string().contains("Stop before calling the model"));
    let snapshot = dir
        .path()
        .join("checkpoint/scopes/agent/agent/snapshots/snapshot_latest.json");
    assert!(
        std::fs::read_to_string(snapshot)
            .unwrap()
            .contains("Remember the checkpoint")
    );
}

#[tokio::test]
async fn rejects_an_empty_session_id() {
    for id in ["", "   "] {
        let message = rejection(with_session(SessionConfig::builder().id(id).build())).await;
        assert_eq!(message, "session.id must be a non-empty string.");
    }
}

#[tokio::test]
async fn sanitizes_the_session_id() {
    let dir = tempfile::tempdir().unwrap();
    let options = with_session(
        SessionConfig::builder()
            .id("azrn:studio:us-west-2:session/abc")
            .dir(dir.path())
            .build(),
    );
    assert_eq!(
        session_id(&assembled(options).await.config),
        "azrn-studio-us-west-2-session-abc"
    );
}

#[tokio::test]
async fn lowercases_the_session_id() {
    let dir = tempfile::tempdir().unwrap();
    let options = with_session(SessionConfig::builder().id("MyProj.v2").dir(dir.path()).build());
    assert_eq!(session_id(&assembled(options).await.config), "myproj-v2");
}

const LARGE_LINES: usize = 400;

fn large_result() -> String {
    (0..LARGE_LINES)
        .map(|line| format!("Line {line}: quarterly budget notes."))
        .collect::<Vec<_>>()
        .join("\n")
}

// https://github.com/strands-agents/harness-sdk/issues/4685
#[tokio::test]
async fn returns_an_offloaded_tool_result_to_the_model_in_full_on_retrieval() {
    let dir = tempfile::tempdir().unwrap();
    let read_large = Arc::new(
        FunctionTool::builder("read_large", "Read a large document.")
            .callback(|_, _| async move { Ok(large_result().into()) }),
    ) as Arc<dyn Tool>;
    let model = MockModel::new()
        .with_turn(MockTurn::content([ContentBlock::ToolUse(ToolUseBlock::new(
            "read_large",
            "tooluse-0",
            json!({}),
        ))]))
        .with_turn(MockTurn::content([ContentBlock::ToolUse(ToolUseBlock::new(
            "retrieve_context",
            "tooluse-1",
            json!({ "reference": "tooluse-0_0" }),
        ))]))
        .with_turn(MockTurn::text("done"));
    model
        .update_config(BaseModelConfig {
            context_window_limit: Some(1_000_000),
            ..Default::default()
        })
        .unwrap();
    let model = Arc::new(model);
    let options = HarnessAgentOptions {
        model: Some(Arc::clone(&model).into()),
        tools: vec![read_large.into()],
        session: Some(SessionConfig::builder().id("retrieval").dir(dir.path()).build().into()),
        builtin_tools: Some(BuiltinToolsOption::List(Vec::new())),
        builtin_plugins: Some(Vec::new()),
        ..quiet()
    };
    let mut agent = create_harness_boxed(options, offline_env()).await.unwrap();
    let limits = InvokeLimits {
        turns: Some(4),
        ..Default::default()
    };
    agent
        .invoke_with(
            "Read the document.",
            InvokeOptions {
                limits: Some(limits),
                ..Default::default()
            },
        )
        .await
        .unwrap();
    let requests = model.requests();
    let seen: Vec<String> = requests[1..]
        .iter()
        .map(|request| serde_json::to_string(request.messages.last().unwrap()).unwrap())
        .collect();
    assert!(seen[0].contains("[Truncated:"), "{}", seen[0]);
    assert!(seen[1].contains("Line 399: quarterly budget notes."));
    let scope = Path::new("scopes").join("agent").join(agent.id());
    let snapshot = std::fs::read_to_string(
        dir.path()
            .join("retrieval")
            .join(&scope)
            .join("snapshots/snapshot_latest.json"),
    )
    .unwrap();
    let snapshot: serde_json::Value = serde_json::from_str(&snapshot).unwrap();
    assert_eq!(
        snapshot["data"]["archive"],
        json!({ "location": "external", "storageType": "LocalFileStorage" })
    );
    assert!(
        dir.path()
            .join("retrieval/context/retrieval")
            .join(&scope)
            .join("tooluse-0_0")
            .exists()
    );
    let entries: Vec<String> = std::fs::read_dir(dir.path())
        .unwrap()
        .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
        .collect();
    assert_eq!(entries, ["retrieval"]);
}

#[tokio::test]
async fn keeps_the_archive_in_memory_without_a_harness_built_session() {
    let in_memory = || -> Arc<dyn Storage> { Arc::new(InMemoryStorage::new()) };
    let manager = || {
        SessionManager::new(SessionManagerConfig {
            storage: Some(in_memory()),
            ..Default::default()
        })
        .unwrap()
    };
    let cases = [
        with_session(false),
        with_session(manager()),
        HarnessAgentOptions {
            session_manager: Some(manager()),
            ..quiet_with_mock()
        },
    ];
    for options in cases {
        assert!(assembled(options).await.config.storage.is_none());
    }
}

#[tokio::test]
async fn backs_the_archive_with_an_explicit_storage() {
    let dir = tempfile::tempdir().unwrap();
    let storage: Arc<dyn Storage> = Arc::new(InMemoryStorage::new());
    let options = HarnessAgentOptions {
        storage: Some(Arc::clone(&storage)),
        ..with_session(SessionConfig::builder().dir(dir.path()).build())
    };
    assert!(Arc::ptr_eq(&assembled(options).await.config.storage.unwrap(), &storage));
}

fn skills_plugins(config: &AgentConfig) -> usize {
    config
        .plugins
        .iter()
        .filter(|plugin| plugin.name() == AGENT_SKILLS_NAME)
        .count()
}

fn with_skills(skills: impl Into<SkillsOption>) -> HarnessAgentOptions {
    HarnessAgentOptions {
        skills: Some(skills.into()),
        ..quiet_with_mock()
    }
}

#[tokio::test]
async fn loads_skills_from_the_skills_directory() {
    let dir = tempfile::tempdir().unwrap();
    write_skill(dir.path(), "hello");
    assert_eq!(skills_plugins(&assembled(with_skills(dir.path())).await.config), 1);
}

#[tokio::test]
async fn passes_an_explicit_missing_skills_path_through_to_the_plugin() {
    let dir = tempfile::tempdir().unwrap();
    assert_eq!(
        skills_plugins(&assembled(with_skills(dir.path().join("absent"))).await.config),
        1
    );
}

#[tokio::test]
async fn skips_the_default_skills_directory_when_it_is_absent() {
    assert!(!Path::new(DEFAULT_SKILLS_DIR).exists());
    assert_eq!(skills_plugins(&assembled(with_skills(true)).await.config), 0);
}

#[tokio::test]
async fn disables_skills_when_skills_is_null() {
    assert_eq!(skills_plugins(&assembled(with_skills(false)).await.config), 0);
}

#[tokio::test]
async fn loads_skills_from_multiple_directories_and_keeps_missing_ones() {
    let a = tempfile::tempdir().unwrap();
    write_skill(a.path(), "hello");
    let sources = [a.path().to_path_buf(), a.path().join("absent")];
    assert_eq!(skills_plugins(&assembled(with_skills(sources)).await.config), 1);
    assert!(matches!(SkillsOption::from(vec!["a", "b"]), SkillsOption::Sources(sources) if sources.len() == 2));
}

#[tokio::test]
async fn disables_skills_when_skills_is_an_empty_array() {
    assert_eq!(
        skills_plugins(&assembled(with_skills(SkillsOption::Sources(Vec::new()))).await.config),
        0
    );
}

#[tokio::test]
async fn does_not_double_add_a_skills_plugin_supplied_via_plugins() {
    let dir = tempfile::tempdir().unwrap();
    write_skill(dir.path(), "hello");
    let existing = AgentSkills::new(AgentSkillsConfig {
        skills: vec![dir.path().into()],
        ..Default::default()
    });
    let options = HarnessAgentOptions {
        plugins: vec![Arc::new(existing)],
        ..with_skills(dir.path())
    };
    assert_eq!(skills_plugins(&assembled(options).await.config), 1);
}

fn with_tools(tools: Vec<Arc<dyn Tool>>) -> HarnessAgentOptions {
    HarnessAgentOptions {
        tools: tools.into_iter().map(ToolSource::Tool).collect(),
        ..quiet_with_mock()
    }
}

#[tokio::test]
async fn rejects_a_built_in_tool_colliding_with_a_consumer_tool() {
    let message = rejection(with_tools(vec![tool(
        "read",
        "A consumer tool that collides with the built-in read.",
    )]))
    .await;
    assert_eq!(
        message,
        "Tool name \"read\" is registered more than once (from a built-in tool and tools). Rename the tool you passed, or drop the built-in via builtinTools / builtinPlugins."
    );
}

#[tokio::test]
async fn rejects_the_built_in_subagent_tool_colliding_with_a_consumer_tool() {
    let message = rejection(with_tools(vec![tool(
        "subagent",
        "Collides with the built-in subagent tool.",
    )]))
    .await;
    assert!(message.contains("Tool name \"subagent\" is registered more than once (from a built-in tool and tools)"));
}

#[tokio::test]
async fn rejects_a_consumer_tool_colliding_with_the_memory_search_tool() {
    let dir = tempfile::tempdir().unwrap();
    let options = HarnessAgentOptions {
        memory: Some(MemoryConfig::builder().dir(dir.path()).build().into()),
        ..with_tools(vec![tool("search_memory", "Collides with the memory manager tool.")])
    };
    assert!(
        rejection(options)
            .await
            .contains("Tool name \"search_memory\" is registered more than once (from tools and memory)")
    );
}

#[tokio::test]
async fn rejects_the_same_consumer_tool_listed_twice() {
    let message = rejection(with_tools(vec![sample_tool(), sample_tool()])).await;
    assert!(message.contains("Tool name \"sample_tool\" is registered more than once (from tools)"));
}

#[tokio::test]
async fn does_not_mention_built_ins_in_a_consumer_only_collision_remedy() {
    let message = rejection(with_tools(vec![sample_tool(), sample_tool()])).await;
    assert!(message.contains("unique name"));
    assert!(!message.contains("built-in"));
}

#[tokio::test]
async fn treats_a_dash_vs_underscore_near_collision_as_a_collision() {
    let message = rejection(with_tools(vec![tool(
        "web-fetch",
        "Collides with web_fetch by '-' vs '_'.",
    )]))
    .await;
    assert!(message.contains("registered more than once"));
}

#[tokio::test]
async fn frees_the_name_for_a_consumer_tool_once_the_built_in_is_dropped() {
    let options = HarnessAgentOptions {
        builtin_tools: Some([BuiltinToolName::Shell, BuiltinToolName::Write, BuiltinToolName::Edit].into()),
        ..with_tools(vec![tool(
            "read",
            "A consumer tool that collides with the built-in read.",
        )])
    };
    let config = assembled(options).await.config;
    let read = config
        .tools
        .iter()
        .find_map(|source| match source {
            ToolSource::Tool(tool) if tool.name() == "read" => Some(tool.tool_spec().description),
            _ => None,
        })
        .unwrap();
    assert!(read.contains("consumer tool that collides"));
}

#[tokio::test]
async fn does_not_name_check_non_tool_entries_in_tools() {
    let options = HarnessAgentOptions {
        tools: vec![ToolSource::List(vec![sample_tool().into()])],
        ..quiet_with_mock()
    };
    let config = assembled(options).await.config;
    let agent = Agent::new(config).unwrap();
    assert!(agent.tool_registry().get("sample_tool").is_some());
}

#[tokio::test]
async fn registers_no_interventions_by_default() {
    assert!(assembled(quiet_with_mock()).await.config.interventions.is_empty());
}

#[tokio::test]
async fn wires_an_interventions_preset() {
    let options = HarnessAgentOptions {
        interventions: Some("ask".into()),
        ..quiet_with_mock()
    };
    let handlers = assembled(options).await.config.interventions;
    assert_eq!(
        handlers.iter().map(|handler| handler.name()).collect::<Vec<_>>(),
        ["strands:human-in-the-loop"]
    );
}

#[tokio::test]
async fn passes_an_intervention_handler_instance_through() {
    let handler: Arc<dyn InterventionHandler> =
        Arc::new(strands::vended_interventions::hitl::HumanInTheLoop::default());
    let options = HarnessAgentOptions {
        interventions: Some(InterventionValue::Handler(Arc::clone(&handler)).into()),
        ..quiet_with_mock()
    };
    let handlers = assembled(options).await.config.interventions;
    assert!(Arc::ptr_eq(&handlers[0], &handler));
}

fn parent_of(assembly: &Assembly) -> Arc<ParentConfig> {
    Arc::clone(&assembly.parent)
}

#[tokio::test]
async fn has_a_subagent_delegate_inherit_the_parent_interventions_and_background_tasks_policy() {
    let options = HarnessAgentOptions {
        interventions: Some("smart".into()),
        background_tasks: Some(false.into()),
        ..quiet_with_mock()
    };
    let parent = parent_of(&assembled(options).await);
    let child = child_options(&parent, &delegable(&parent.tools), ChildSpec::default(), &offline_env()).unwrap();
    assert!(
        matches!(child.interventions, Some(InterventionsOption::Value(InterventionValue::Text(text))) if text == "smart")
    );
    assert!(matches!(child.background_tasks, Some(Toggle::Off)));
    assert_eq!(child.printer, Some(false));
}

#[cfg(feature = "openai")]
#[tokio::test]
async fn forwards_a_per_tool_web_fetch_config_to_the_delegate_as_a_pinned_mapping() {
    let mapping = BuiltinToolsConfig::builder()
        .web_fetch(crate::WebFetchConfig::builder().model("openai/gpt-5-mini").build())
        .shell(ShellConfig::builder().description("Run it.").build())
        .build();
    let options = HarnessAgentOptions {
        builtin_tools: Some(mapping.into()),
        ..quiet_with_mock()
    };
    let parent = parent_of(&assembled(options).await);
    let spec = ChildSpec {
        tools: strings(&["web_fetch", "read", "shell"]),
        ..Default::default()
    };
    let child = child_options(&parent, &delegable(&parent.tools), spec, &offline_env()).unwrap();
    let Some(BuiltinToolsOption::Mapping(pinned)) = child.builtin_tools else {
        panic!("a pinned mapping")
    };
    assert_eq!(pinned.all, None);
    assert_eq!(
        pinned.shell,
        Some(ShellConfig::builder().description("Run it.").build().into())
    );
    assert_eq!(pinned.read, Some(true.into()));
    assert_eq!(pinned.write, Some(false));
    assert_eq!(pinned.edit, Some(false));
    let Some(crate::Setting::Config(web_fetch)) = pinned.web_fetch else {
        panic!("web_fetch config")
    };
    assert!(matches!(web_fetch.model, Some(ModelSource::Id(model)) if model == "openai/gpt-5-mini"));
    // The parent's model has no native search, so it forwards web_search off to keep the child quiet.
    assert_eq!(pinned.web_search, Some(false.into()));
    assert_eq!(pinned.programmatic_tool_caller, Some(false.into()));
    assert_eq!(pinned.subagent, Some(false.into()));
}

#[cfg(feature = "mcp")]
#[tokio::test]
async fn loads_mcp_servers_through_the_sdk_resilient_and_prefixed_by_server_name() {
    let servers = json!({ "srv": { "command": "strands-harness-test-missing-server" } });
    let options = HarnessAgentOptions {
        mcp_servers: Some(crate::McpServersOption::Json(servers.as_object().unwrap().clone())),
        ..quiet_with_mock()
    };
    let config = assembled(options).await.config;
    let clients: Vec<&strands::mcp::McpClient> = config
        .tools
        .iter()
        .filter_map(|source| match source {
            ToolSource::McpClient(client) => Some(client),
            _ => None,
        })
        .collect();
    assert_eq!(clients.len(), 1);
    assert_eq!(clients[0].client_name(), "srv");
    assert!(clients[0].continue_on_error());
}

#[cfg(not(feature = "mcp"))]
#[tokio::test]
async fn names_the_feature_mcp_servers_need() {
    let options = HarnessAgentOptions {
        mcp_servers: Some("./mcp.json".into()),
        ..quiet_with_mock()
    };
    let error = assemble(options, &offline_env()).await.err().unwrap();
    assert_eq!(
        error.to_string(),
        "mcp_servers needs the strands-harness feature \"mcp\"; enable it to connect MCP servers."
    );
}

#[tokio::test]
async fn does_not_touch_mcp_when_no_servers_are_given() {
    let config = assembled(quiet_with_mock()).await.config;
    assert!(config.tools.iter().all(|source| matches!(source, ToolSource::Tool(_))));
}

mod subagent_delegate_built_child {
    use super::*;

    async fn build_child(options: HarnessAgentOptions, spec: ChildSpec) -> Assembly {
        let parent = parent_of(&assembled(options).await);
        let child = child_options(&parent, &delegable(&parent.tools), spec, &offline_env()).unwrap();
        assembled(child).await
    }

    #[tokio::test]
    async fn narrows_the_built_child_to_the_requested_subset_dropping_the_rest() {
        let options = HarnessAgentOptions {
            builtin_tools: Some([BuiltinToolName::Read, BuiltinToolName::Shell, BuiltinToolName::Subagent].into()),
            ..quiet_with_mock()
        };
        let spec = ChildSpec {
            tools: strings(&["read"]),
            ..Default::default()
        };
        let names = tool_names(&build_child(options, spec).await.config);
        assert!(names.contains(&"read".to_owned()));
        assert!(!names.contains(&"shell".to_owned()));
    }

    #[tokio::test]
    async fn hands_the_built_child_every_consumer_tool_when_the_model_does_not_narrow() {
        let names = tool_names(
            &build_child(with_tools(vec![sample_tool()]), ChildSpec::default())
                .await
                .config,
        );
        assert!(names.contains(&"sample_tool".to_owned()));
    }

    #[tokio::test]
    async fn gives_the_built_child_a_recall_only_memory_view() {
        let dir = tempfile::tempdir().unwrap();
        let options = HarnessAgentOptions {
            memory: Some(MemoryConfig::builder().dir(dir.path()).build().into()),
            ..quiet_with_mock()
        };
        let parent = parent_of(&assembled(options).await);
        let child = child_options(&parent, &delegable(&parent.tools), ChildSpec::default(), &offline_env()).unwrap();
        assert!(matches!(child.memory, Some(MemoryOption::Off)));
        assert!(matches!(child.memory_manager, Some(MemoryManagerSource::Manager(_))));
    }

    #[tokio::test]
    async fn builds_the_child_with_sessions_forced_off() {
        let dir = tempfile::tempdir().unwrap();
        let options = with_session(SessionConfig::builder().dir(dir.path()).build());
        assert!(
            build_child(options, ChildSpec::default())
                .await
                .config
                .session_manager
                .is_none()
        );
    }

    #[tokio::test]
    async fn registers_the_inherited_interventions_gate_on_the_built_child() {
        let options = HarnessAgentOptions {
            interventions: Some("ask".into()),
            ..quiet_with_mock()
        };
        let handlers = build_child(options, ChildSpec::default()).await.config.interventions;
        assert_eq!(handlers.len(), 1);
        assert_eq!(handlers[0].name(), "strands:human-in-the-loop");
    }

    #[tokio::test]
    async fn keeps_its_own_subagent_tool_so_a_delegate_can_sub_delegate() {
        let names = tool_names(&build_child(quiet_with_mock(), ChildSpec::default()).await.config);
        assert!(names.contains(&"subagent".to_owned()));
    }

    #[cfg(feature = "openai")]
    #[tokio::test]
    async fn carries_explicit_web_search_onto_a_narrowed_delegate() {
        let options = HarnessAgentOptions {
            model: Some("openai/gpt-5.6-sol".into()),
            builtin_tools: Some(
                [
                    BuiltinToolName::Read,
                    BuiltinToolName::WebSearch,
                    BuiltinToolName::Subagent,
                ]
                .into(),
            ),
            ..quiet()
        };
        let spec = ChildSpec {
            tools: strings(&["read"]),
            ..Default::default()
        };
        let plan = build_child(options, spec).await.model_plan.unwrap();
        assert_eq!(plan.params.unwrap()["tools"], json!([{ "type": "web_search" }]));
    }

    #[cfg(feature = "openai")]
    #[tokio::test]
    async fn keeps_native_search_on_a_narrowed_delegate_of_a_default_configured_parent() {
        let options = HarnessAgentOptions {
            model: Some("openai/gpt-5.6-sol".into()),
            ..quiet()
        };
        let spec = ChildSpec {
            tools: strings(&["read"]),
            ..Default::default()
        };
        let plan = build_child(options, spec).await.model_plan.unwrap();
        assert_eq!(plan.provider, crate::models::Provider::OpenAI);
        assert_eq!(plan.params.unwrap()["tools"], json!([{ "type": "web_search" }]));
    }

    #[cfg(feature = "mcp")]
    #[tokio::test]
    async fn carries_the_exa_fallback_onto_a_narrowed_delegate() {
        let options = HarnessAgentOptions {
            builtin_tools: Some(
                BuiltinToolsConfig::builder()
                    .web_search(crate::WebSearchSetting::Exa)
                    .build()
                    .into(),
            ),
            ..quiet_with_mock()
        };
        let spec = ChildSpec {
            tools: strings(&["read"]),
            ..Default::default()
        };
        assert!(tool_names(&build_child(options, spec).await.config).contains(&"web_search".to_owned()));
    }

    #[cfg(feature = "bedrock")]
    #[tokio::test]
    async fn gives_delegates_of_a_default_bedrock_parent_agentcore_web_search() {
        let narrowed = ChildSpec {
            tools: strings(&["read"]),
            ..Default::default()
        };
        for spec in [narrowed, ChildSpec::default()] {
            assert!(tool_names(&build_child(quiet(), spec).await.config).contains(&"web_search".to_owned()));
        }
    }

    #[tokio::test]
    async fn hands_delegates_the_callers_web_search_when_the_built_in_is_off() {
        let options = || HarnessAgentOptions {
            tools: vec![tool("web_search", "Search.").into()],
            builtin_tools: Some(BuiltinToolsConfig::builder().web_search(false).build().into()),
            ..quiet_with_mock()
        };
        let inherit_all = build_child(options(), ChildSpec::default()).await;
        let description = inherit_all.config.tools.iter().find_map(|source| match source {
            ToolSource::Tool(tool) if tool.name() == "web_search" => Some(tool.description().to_owned()),
            _ => None,
        });
        assert_eq!(description.as_deref(), Some("Search."));
        let narrowed = ChildSpec {
            tools: strings(&["read"]),
            ..Default::default()
        };
        assert!(!tool_names(&build_child(options(), narrowed).await.config).contains(&"web_search".to_owned()));
    }

    #[cfg(feature = "mcp")]
    fn client_names(tools: &[ToolSource]) -> Vec<String> {
        tools
            .iter()
            .filter_map(|source| match source {
                ToolSource::McpClient(client) => Some(client.client_name().to_owned()),
                _ => None,
            })
            .collect()
    }

    #[cfg(feature = "mcp")]
    fn subagent_schema(config: &AgentConfig) -> serde_json::Value {
        let tool = config
            .tools
            .iter()
            .find_map(|source| match source {
                ToolSource::Tool(tool) if tool.name() == "subagent" => Some(tool),
                _ => None,
            })
            .unwrap();
        tool.tool_spec().input_schema.unwrap()
    }

    #[cfg(feature = "mcp")]
    #[tokio::test]
    async fn inherits_every_parent_mcp_server_also_on_a_narrowed_delegate() {
        let servers = json!({ "alpha": { "command": "node" }, "beta": { "command": "node" } });
        let options = HarnessAgentOptions {
            mcp_servers: Some(crate::McpServersOption::Json(servers.as_object().unwrap().clone())),
            ..quiet_with_mock()
        };
        let assembly = assembled(options).await;
        assert!(
            subagent_schema(&assembly.config)["properties"]
                .get("mcp_servers")
                .is_none()
        );
        let parent = parent_of(&assembly);
        let delegable = delegable(&parent.tools);
        let child = |tools: Option<Vec<String>>| {
            let spec = ChildSpec {
                tools,
                ..Default::default()
            };
            client_names(&child_options(&parent, &delegable, spec, &offline_env()).unwrap().tools)
        };
        assert_eq!(child(None), ["alpha", "beta"]);
        assert_eq!(child(strings(&["read"])), ["alpha", "beta"]);
    }

    #[cfg(feature = "mcp")]
    #[tokio::test]
    async fn hands_mcp_clients_passed_in_tools_to_a_narrowed_delegate_without_offering_them_as_tools() {
        use strands::mcp::{McpClient, McpClientConfig, McpClientOptions, McpLoadServersOptions, McpServersSource};

        let servers = json!({ "alpha": { "command": "node" } });
        let mut clients = McpClient::load_servers(
            McpServersSource::Json(servers.as_object().unwrap().clone()),
            McpClientOptions::default(),
            McpLoadServersOptions {
                prefix_with_server_name: true,
            },
        )
        .await
        .unwrap();
        clients.push(
            McpClient::new(McpClientConfig {
                url: Some("http://127.0.0.1:9/mcp".to_owned()),
                options: McpClientOptions {
                    prefix: Some("bare".to_owned()),
                    ..Default::default()
                },
                ..Default::default()
            })
            .unwrap(),
        );
        let options = HarnessAgentOptions {
            tools: clients.into_iter().map(ToolSource::McpClient).collect(),
            ..quiet_with_mock()
        };
        let parent = parent_of(&assembled(options).await);
        let options = subagent_tool_options(&parent, crate::SubagentConfig::default(), &offline_env());
        assert!(!options.inherited_tools.contains(&"alpha".to_owned()));
        let spec = ChildSpec {
            tools: strings(&["read"]),
            ..Default::default()
        };
        let child = child_options(&parent, &delegable(&parent.tools), spec, &offline_env()).unwrap();
        assert_eq!(client_names(&child.tools).len(), 2);
    }
}

mod subagent_selectable_set {
    use super::*;

    #[tokio::test]
    async fn keeps_subagent_for_sub_delegation_and_drops_web_search() {
        let parent = parent_of(&assembled(quiet_with_mock()).await);
        let options = subagent_tool_options(&parent, crate::SubagentConfig::default(), &offline_env());
        assert!(options.inherited_tools.contains(&"subagent".to_owned()));
        assert!(!options.inherited_tools.contains(&"web_search".to_owned()));
    }

    #[tokio::test]
    async fn adds_consumer_tools_and_the_depth_bound() {
        let options = HarnessAgentOptions {
            builtin_tools: Some(
                BuiltinToolsConfig::builder()
                    .subagent(crate::SubagentConfig { max_depth: Some(1) })
                    .build()
                    .into(),
            ),
            ..with_tools(vec![sample_tool()])
        };
        let assembly = assembled(options).await;
        let parent = parent_of(&assembly);
        let config = resolve_builtin_tools(Some(&BuiltinToolsOption::Mapping(parent.builtin_tools.clone())))
            .subagent_config()
            .unwrap();
        let options = subagent_tool_options(&parent, config, &offline_env());
        assert_eq!(options.max_depth, Some(1));
        assert!(options.inherited_tools.contains(&"sample_tool".to_owned()));
    }
}

mod create_harness_memory {
    use super::*;

    fn with_memory(memory: impl Into<MemoryOption>) -> HarnessAgentOptions {
        HarnessAgentOptions {
            memory: Some(memory.into()),
            ..quiet_with_mock()
        }
    }

    #[tokio::test]
    async fn attaches_a_memory_manager_by_default() {
        let dir = tempfile::tempdir().unwrap();
        let config = assembled(with_memory(MemoryConfig::builder().dir(dir.path()).build()))
            .await
            .config;
        assert!(matches!(config.memory_manager, Some(MemoryManagerSource::Manager(_))));
    }

    #[tokio::test]
    async fn attaches_no_memory_manager_when_memory_is_disabled() {
        assert!(assembled(with_memory(false)).await.config.memory_manager.is_none());
    }

    #[tokio::test]
    async fn passes_a_memory_manager_given_as_memory_straight_through() {
        let config = assembled(with_memory(custom_manager())).await.config;
        assert!(matches!(config.memory_manager, Some(MemoryManagerSource::Manager(_))));
    }

    #[tokio::test]
    async fn lets_a_memory_manager_escape_hatch_win_over_a_memory_config() {
        let dir = tempfile::tempdir().unwrap();
        let options = HarnessAgentOptions {
            memory_manager: Some(MemoryManagerConfig::default().into()),
            ..with_memory(MemoryConfig::builder().dir(dir.path()).build())
        };
        assert!(matches!(
            assembled(options).await.config.memory_manager,
            Some(MemoryManagerSource::Config(_))
        ));
    }

    #[tokio::test]
    async fn manages_consumer_memory_stores_under_the_harness_policy() {
        let options = with_memory(MemoryConfig {
            stores: vec![Arc::new(Recall)],
            ..Default::default()
        });
        let config = assembled(options).await.config;
        let Some(MemoryManagerSource::Manager(manager)) = config.memory_manager else {
            panic!("a manager")
        };
        let names: Vec<String> = manager
            .get_tools()
            .into_iter()
            .flat_map(ToolSource::into_tools)
            .map(|tool| tool.name().to_owned())
            .collect();
        assert!(names.contains(&"search_memory".to_owned()));
    }
}

mod subagent_memory_and_plugin_forwarding {
    use super::*;

    struct PolicyPlugin;

    #[async_trait]
    impl Plugin for PolicyPlugin {
        fn name(&self) -> &str {
            "policy"
        }

        async fn init_agent(&self, _agent: &mut strands::agent::LocalAgent) -> strands::Result<()> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn disables_the_delegates_memory_when_the_parent_uses_a_custom_memory_manager() {
        let options = HarnessAgentOptions {
            memory_manager: Some(custom_manager().into()),
            memory: None,
            ..quiet_with_mock()
        };
        let parent = parent_of(&assembled(options).await);
        assert!(matches!(parent.memory, Some(MemoryOption::Off)));
    }

    #[tokio::test]
    async fn forwards_the_parent_memory_stores_to_the_delegate_so_it_shares_the_same_backend() {
        let options = HarnessAgentOptions {
            memory: Some(
                MemoryConfig {
                    stores: vec![Arc::new(Recall)],
                    ..Default::default()
                }
                .into(),
            ),
            ..quiet_with_mock()
        };
        let parent = parent_of(&assembled(options).await);
        let Some(MemoryOption::On(memory)) = &parent.memory else {
            panic!("memory on")
        };
        assert_eq!(
            memory.stores.iter().map(|store| store.name()).collect::<Vec<_>>(),
            ["custom"]
        );
    }

    #[tokio::test]
    async fn forwards_consumer_plugins_to_the_delegate() {
        let options = HarnessAgentOptions {
            plugins: vec![Arc::new(PolicyPlugin)],
            ..quiet_with_mock()
        };
        let parent = parent_of(&assembled(options).await);
        assert_eq!(
            parent.plugins.iter().map(|plugin| plugin.name()).collect::<Vec<_>>(),
            ["policy"]
        );
    }
}

#[test]
fn sanitize_session_id_falls_back_to_default() {
    assert_eq!(sanitize_session_id("  "), "default");
    assert_eq!(sanitize_session_id("A b"), "a-b");
}

/// A factory that records what each configurable built-in is built with, then builds it for real.
mod builtin_tool_factories {
    use std::cell::RefCell;

    use super::*;
    use crate::factory::{BUILTIN_TOOL_FACTORY, BuiltinToolFactory, SubagentToolOptions};
    use crate::types::ProgrammaticToolCallerConfig;

    thread_local! {
        static CALLS: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
    }

    fn record(call: String) {
        CALLS.with(|calls| calls.borrow_mut().push(call));
    }

    const RECORDING: BuiltinToolFactory = BuiltinToolFactory {
        shell: |config| {
            record(format!("shell {:?}", config.description));
            (BUILTIN_TOOL_FACTORY.shell)(config)
        },
        programmatic_tool_caller: |config: &ProgrammaticToolCallerConfig| {
            record(format!(
                "programmatic_tool_caller {:?} {:?}",
                config.allowed_tools, config.timeout
            ));
            (BUILTIN_TOOL_FACTORY.programmatic_tool_caller)(config)
        },
        subagent: |options: SubagentToolOptions| {
            record(format!("subagent {:?}", options.max_depth));
            (BUILTIN_TOOL_FACTORY.subagent)(options)
        },
        web_search: |mode, env| {
            record(format!("web_search {mode:?} {:?}", env.get("AWS_REGION")));
            (BUILTIN_TOOL_FACTORY.web_search)(mode, env)
        },
        ..BUILTIN_TOOL_FACTORY
    };

    #[cfg(feature = "bedrock")]
    async fn web_search_calls(builtin_tools: Option<BuiltinToolsConfig>) -> Vec<String> {
        CALLS.with(|calls| calls.borrow_mut().clear());
        let options = HarnessAgentOptions {
            builtin_tools: builtin_tools.map(Into::into),
            ..quiet()
        };
        let env = crate::test_support::env(&[("AWS_REGION", "eu-west-1")]);
        assemble_with(options, &env, &RECORDING).await.unwrap();
        only(&CALLS.with(|calls| calls.borrow().clone()), "web_search")
    }

    #[cfg(feature = "bedrock")]
    #[tokio::test]
    async fn builds_the_agentcore_web_search_tool_on_bedrock_from_the_harness_environment() {
        assert_eq!(
            web_search_calls(None).await,
            ["web_search AgentCore Some(\"eu-west-1\")"]
        );
    }

    #[cfg(all(feature = "bedrock", feature = "mcp"))]
    #[tokio::test]
    async fn serves_an_explicit_exa_selection_on_bedrock_instead_of_agentcore() {
        let exa = BuiltinToolsConfig::builder()
            .web_search(crate::WebSearchSetting::Exa)
            .build();
        assert_eq!(
            web_search_calls(Some(exa)).await,
            ["web_search Exa Some(\"eu-west-1\")"]
        );
    }

    async fn calls_for(builtin_tools: BuiltinToolsConfig) -> (Vec<String>, Vec<String>) {
        CALLS.with(|calls| calls.borrow_mut().clear());
        let options = HarnessAgentOptions {
            builtin_tools: Some(builtin_tools.into()),
            ..quiet_with_mock()
        };
        let assembly = assemble_with(options, &offline_env(), &RECORDING).await.unwrap();
        (CALLS.with(|calls| calls.borrow().clone()), tool_names(&assembly.config))
    }

    fn only(calls: &[String], name: &str) -> Vec<String> {
        calls.iter().filter(|call| call.starts_with(name)).cloned().collect()
    }

    #[tokio::test]
    async fn builds_each_tool_from_its_factory_with_its_per_tool_config() {
        let shell = BuiltinToolsConfig::builder()
            .shell(ShellConfig::builder().description("Run a command.").build())
            .build();
        let (calls, names) = calls_for(shell).await;
        assert!(names.contains(&"shell".to_owned()));
        assert_eq!(only(&calls, "shell"), ["shell Some(\"Run a command.\")"]);

        let caller = ProgrammaticToolCallerConfig {
            allowed_tools: Some(vec!["read".to_owned()]),
            timeout: Some(Some(60.0)),
        };
        let (calls, names) = calls_for(BuiltinToolsConfig::builder().programmatic_tool_caller(caller).build()).await;
        assert!(names.contains(&"programmatic_tool_caller".to_owned()));
        assert_eq!(
            only(&calls, "programmatic"),
            ["programmatic_tool_caller Some([\"read\"]) Some(Some(60.0))"]
        );

        let unbounded = ProgrammaticToolCallerConfig {
            timeout: Some(None),
            ..Default::default()
        };
        let (calls, _) = calls_for(
            BuiltinToolsConfig::builder()
                .programmatic_tool_caller(unbounded)
                .build(),
        )
        .await;
        assert_eq!(
            only(&calls, "programmatic"),
            ["programmatic_tool_caller None Some(None)"]
        );

        let subagent = crate::SubagentConfig { max_depth: Some(1) };
        let (calls, names) = calls_for(BuiltinToolsConfig::builder().subagent(subagent).build()).await;
        assert!(names.contains(&"subagent".to_owned()));
        assert_eq!(only(&calls, "subagent"), ["subagent Some(1)"]);
    }

    #[tokio::test]
    async fn builds_each_tool_from_its_factory_with_no_config_when_enabled_with_true() {
        let (calls, _) = calls_for(
            BuiltinToolsConfig::builder()
                .shell(true)
                .programmatic_tool_caller(true)
                .subagent(true)
                .build(),
        )
        .await;
        assert_eq!(only(&calls, "shell"), ["shell None"]);
        assert_eq!(only(&calls, "programmatic"), ["programmatic_tool_caller None None"]);
        assert_eq!(only(&calls, "subagent"), ["subagent None"]);
    }
}

/// The environment plugin through `create_harness`.
mod builtin_plugins {
    use super::*;

    #[test]
    fn throws_on_an_unknown_built_in_plugin_name() {
        let error = "nope".parse::<BuiltinPluginName>().unwrap_err();
        assert!(error.to_string().contains("Unknown built-in plugin"));
    }

    #[tokio::test]
    async fn environment_is_enabled_by_default_and_opts_out_with_an_empty_list() {
        let config = assembled(quiet_with_mock()).await.config;
        assert!(
            config
                .plugins
                .iter()
                .any(|plugin| plugin.name() == "strands:environment")
        );
        let bare = HarnessAgentOptions {
            builtin_plugins: Some(Vec::new()),
            ..quiet_with_mock()
        };
        let config = assembled(bare).await.config;
        assert!(
            !config
                .plugins
                .iter()
                .any(|plugin| plugin.name() == "strands:environment")
        );
    }

    #[tokio::test]
    async fn a_consumer_plugin_named_like_a_built_in_replaces_it() {
        let options = HarnessAgentOptions {
            plugins: vec![Arc::new(crate::EnvironmentContext::default())],
            ..quiet_with_mock()
        };
        let config = assembled(options).await.config;
        assert_eq!(
            config
                .plugins
                .iter()
                .filter(|plugin| plugin.name() == "strands:environment")
                .count(),
            1
        );
    }
}

#[cfg(feature = "mcp")]
mod connected_mcp_delegates;
#[cfg(feature = "openai")]
mod openai_cache;
mod subagent_tool;