appam 0.1.1

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

use std::path::Path;
use std::sync::Arc;

use anyhow::{Context, Result};

use super::runtime_agent::RuntimeAgent;
use crate::tools::{AsyncTool, Tool, ToolRegistry};

/// Provider-specific reasoning configuration.
///
/// Wraps reasoning configurations for different LLM providers to enable
/// type-safe, provider-specific reasoning settings in the AgentBuilder.
///
/// # Examples
///
/// ```no_run
/// # use appam::agent::{AgentBuilder, ReasoningProvider};
/// # use appam::llm::LlmProvider;
/// # use appam::llm::openai::{ReasoningConfig, ReasoningEffort};
/// # use anyhow::Result;
/// # fn main() -> Result<()> {
/// // OpenAI-specific reasoning
/// let agent = AgentBuilder::new("agent")
///     .provider(LlmProvider::OpenAI)
///     .reasoning(ReasoningProvider::OpenAI(
///         ReasoningConfig::high_effort()
///     ))
///     .build()?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub enum ReasoningProvider {
    /// OpenAI Responses API reasoning configuration
    OpenAI(crate::llm::openai::ReasoningConfig),
    /// OpenRouter (Completions or Responses) reasoning configuration
    OpenRouter(crate::llm::openrouter::config::ReasoningConfig),
}

/// Fluent builder for constructing [`RuntimeAgent`] instances.
///
/// The builder keeps configuration explicit and local to the calling site while
/// reusing the same runtime, tool registry, and provider abstraction used by
/// TOML-loaded agents.
///
/// Prefer this type when you need:
///
/// - provider-specific tuning such as reasoning, caching, or service tiers
/// - managed tool registration without writing TOML
/// - history, tracing, or continuation overrides bound to one agent instance
/// - deterministic construction that validates inputs before the first request
///
/// # Examples
///
/// ```no_run
/// use appam::agent::AgentBuilder;
/// use anyhow::Result;
///
/// # fn main() -> Result<()> {
/// let agent = AgentBuilder::new("my-agent")
///     .model("anthropic/claude-sonnet-4-5")
///     .system_prompt("You are a helpful AI assistant.")
///     .build()?;
/// # Ok(())
/// # }
/// ```
///
/// With tools:
///
/// ```no_run
/// # use appam::agent::AgentBuilder;
/// # use anyhow::Result;
/// # use std::sync::Arc;
/// # use appam::tools::{Tool, ToolRegistry};
/// # struct MyTool;
/// # impl Tool for MyTool {
/// #     fn name(&self) -> &str { "my_tool" }
/// #     fn spec(&self) -> Result<appam::llm::ToolSpec> { todo!() }
/// #     fn execute(&self, _: serde_json::Value) -> Result<serde_json::Value> { todo!() }
/// # }
/// # fn main() -> Result<()> {
/// let agent = AgentBuilder::new("my-agent")
///     .system_prompt("You are a helpful assistant.")
///     .with_tool(Arc::new(MyTool))
///     .build()?;
/// # Ok(())
/// # }
/// ```
pub struct AgentBuilder {
    name: String,
    provider: Option<crate::llm::LlmProvider>,
    model: Option<String>,
    system_prompt: Option<String>,
    system_prompt_file: Option<std::path::PathBuf>,
    registry: Option<Arc<ToolRegistry>>,
    tools: Vec<Arc<dyn Tool>>,
    async_tools: Vec<Arc<dyn AsyncTool>>,

    // API keys (override config file and env vars)
    anthropic_api_key: Option<String>,
    openrouter_api_key: Option<String>,
    vertex_api_key: Option<String>,

    // Anthropic-specific configuration
    anthropic_pricing_model: Option<String>,
    thinking: Option<crate::llm::anthropic::ThinkingConfig>,
    caching: Option<crate::llm::anthropic::CachingConfig>,
    tool_choice: Option<crate::llm::anthropic::ToolChoiceConfig>,
    effort: Option<crate::llm::anthropic::EffortLevel>,
    beta_features: Option<crate::llm::anthropic::BetaFeatures>,
    retry: Option<crate::llm::anthropic::RetryConfig>,
    rate_limiter: Option<crate::llm::anthropic::RateLimiterConfig>,

    // Provider-specific reasoning configuration
    reasoning: Option<ReasoningProvider>,

    // OpenRouter-specific configuration
    provider_preferences: Option<crate::llm::openrouter::config::ProviderPreferences>,
    openrouter_transforms: Option<Vec<String>>,
    openrouter_models: Option<Vec<String>>,

    // OpenAI-specific configuration
    openai_api_key: Option<String>,
    openai_codex_access_token: Option<String>,
    openai_service_tier: Option<crate::llm::openai::ServiceTier>,
    openai_text_verbosity: Option<crate::llm::openai::TextVerbosity>,
    openai_pricing_model: Option<String>,

    // Shared LLM parameters
    max_tokens: Option<u32>,
    temperature: Option<f32>,
    top_p: Option<f32>,
    top_k: Option<u32>,
    stop_sequences: Option<Vec<String>>,

    // Logging configuration overrides
    logs_dir: Option<std::path::PathBuf>,
    log_level: Option<String>,
    log_format: Option<crate::config::LogFormat>,
    enable_traces: Option<bool>,
    trace_format: Option<crate::config::TraceFormat>,

    // History configuration overrides
    history_enabled: Option<bool>,
    history_db_path: Option<std::path::PathBuf>,
    history_auto_save: Option<bool>,
    provider_parallel_tool_calls: bool,
    max_concurrent_tool_executions: usize,

    // Session continuation configuration
    required_completion_tools: Vec<Arc<dyn Tool>>,
    max_continuations: usize,
    continuation_message: Option<String>,
}

impl AgentBuilder {
    /// Create a new builder for the supplied agent name.
    ///
    /// The name is used for session metadata, trace output, and managed-state
    /// routing. It should therefore be stable and human meaningful.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use appam::agent::AgentBuilder;
    ///
    /// let builder = AgentBuilder::new("my-agent");
    /// ```
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            provider: None,
            model: None,
            system_prompt: None,
            system_prompt_file: None,
            registry: None,
            tools: Vec::new(),
            async_tools: Vec::new(),
            anthropic_api_key: None,
            openrouter_api_key: None,
            vertex_api_key: None,
            openai_api_key: None,
            openai_codex_access_token: None,
            openai_service_tier: None,
            openai_text_verbosity: None,
            openai_pricing_model: None,
            anthropic_pricing_model: None,
            thinking: None,
            caching: None,
            tool_choice: None,
            effort: None,
            beta_features: None,
            retry: None,
            rate_limiter: None,
            reasoning: None,
            provider_preferences: None,
            openrouter_transforms: None,
            openrouter_models: None,
            max_tokens: None,
            temperature: None,
            top_p: None,
            top_k: None,
            stop_sequences: None,
            logs_dir: None,
            log_level: None,
            log_format: None,
            enable_traces: None,
            trace_format: None,
            history_enabled: None,
            history_db_path: None,
            history_auto_save: None,
            provider_parallel_tool_calls: false,
            max_concurrent_tool_executions: 1,
            required_completion_tools: Vec::new(),
            max_continuations: 2,
            continuation_message: None,
        }
    }

    /// Override provider inference with an explicit [`crate::llm::LlmProvider`].
    ///
    /// This is most useful when your model string is ambiguous, when you want
    /// to route the same model family through a different backend, or when the
    /// provider carries extra metadata such as Azure or Bedrock settings.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// # use appam::agent::{Agent, AgentBuilder};
    /// # use appam::llm::LlmProvider;
    /// let builder = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::Anthropic)
    ///     .model("claude-sonnet-4-5");
    /// ```
    pub fn provider(mut self, provider: crate::llm::LlmProvider) -> Self {
        self.provider = Some(provider);
        self
    }

    /// Set the model identifier sent to the selected provider.
    ///
    /// Appam accepts provider-prefixed shared model strings such as
    /// `"openai/gpt-5.4"` as well as provider-native identifiers when the
    /// selected provider expects them.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// # use appam::agent::AgentBuilder;
    /// let builder = AgentBuilder::new("agent")
    ///     .model("anthropic/claude-sonnet-4-5");
    /// ```
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// Set Anthropic API key programmatically.
    ///
    /// This overrides the API key from:
    /// - `appam.toml` config file
    /// - `ANTHROPIC_API_KEY` environment variable
    ///
    /// # Configuration Priority
    ///
    /// Programmatic configuration (highest priority) > Environment variables > Config file > Defaults
    ///
    /// # Examples
    ///
    /// ```ignore
    /// # use appam::agent::AgentBuilder;
    /// # use appam::llm::LlmProvider;
    /// let agent = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::Anthropic)
    ///     .anthropic_api_key("sk-ant-...")
    ///     .model("claude-sonnet-4-5")
    ///     .system_prompt("You are helpful.")
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn anthropic_api_key(mut self, key: impl Into<String>) -> Self {
        self.anthropic_api_key = Some(key.into());
        self
    }

    /// Set OpenRouter API key programmatically.
    ///
    /// This overrides the API key from:
    /// - `appam.toml` config file
    /// - `OPENROUTER_API_KEY` environment variable
    ///
    /// # Configuration Priority
    ///
    /// Programmatic configuration (highest priority) > Environment variables > Config file > Defaults
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use appam::llm::LlmProvider;
    /// let agent = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::OpenRouterCompletions)
    ///     .openrouter_api_key("sk-or-v1-...")
    ///     .model("openai/gpt-5")
    ///     .system_prompt("You are helpful.")
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn openrouter_api_key(mut self, key: impl Into<String>) -> Self {
        self.openrouter_api_key = Some(key.into());
        self
    }

    /// Enable Anthropic extended thinking with token budget.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use appam::llm::LlmProvider;
    /// # use appam::llm::anthropic::ThinkingConfig;
    /// let agent = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::Anthropic)
    ///     .model("claude-sonnet-4-5")
    ///     .thinking(ThinkingConfig::enabled(10000))
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn thinking(mut self, config: crate::llm::anthropic::ThinkingConfig) -> Self {
        self.thinking = Some(config);
        self
    }

    /// Enable Anthropic prompt caching.
    ///
    /// This maps to Anthropic's top-level `cache_control` request field on the
    /// direct Anthropic and Azure Anthropic transports. Anthropic then applies
    /// the breakpoint to the last cacheable block in the request.
    ///
    /// On AWS Bedrock, Appam instead injects block-level `cache_control`
    /// checkpoints into supported Anthropic fields because Bedrock's InvokeModel
    /// integration uses explicit checkpoints rather than Anthropic's top-level
    /// helper.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use appam::llm::LlmProvider;
    /// # use appam::llm::anthropic::CachingConfig;
    /// let agent = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::Anthropic)
    ///     .caching(CachingConfig {
    ///         enabled: true,
    ///         ttl: appam::llm::anthropic::CacheTTL::OneHour,
    ///     })
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn caching(mut self, config: crate::llm::anthropic::CachingConfig) -> Self {
        self.caching = Some(config);
        self
    }

    /// Set Anthropic tool choice strategy.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use appam::llm::LlmProvider;
    /// # use appam::llm::anthropic::ToolChoiceConfig;
    /// let agent = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::Anthropic)
    ///     .tool_choice(ToolChoiceConfig::Auto { disable_parallel_tool_use: false })
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn tool_choice(mut self, config: crate::llm::anthropic::ToolChoiceConfig) -> Self {
        self.tool_choice = Some(config);
        self
    }

    /// Set the effort level for Claude's token spending.
    ///
    /// Controls how eagerly Claude spends tokens when responding. Affects text
    /// responses, tool calls, and extended thinking. Serialized as
    /// `output_config.effort` in the request body.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use appam::llm::LlmProvider;
    /// # use appam::llm::anthropic::EffortLevel;
    /// let agent = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::Anthropic)
    ///     .model("claude-opus-4-6")
    ///     .effort(EffortLevel::Max)
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn effort(mut self, level: crate::llm::anthropic::EffortLevel) -> Self {
        self.effort = Some(level);
        self
    }

    /// Enable Anthropic beta features.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use appam::llm::LlmProvider;
    /// # use appam::llm::anthropic::BetaFeatures;
    /// let agent = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::Anthropic)
    ///     .beta_features(BetaFeatures {
    ///         interleaved_thinking: true,
    ///         context_1m: true,
    ///         ..Default::default()
    ///     })
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn beta_features(mut self, features: crate::llm::anthropic::BetaFeatures) -> Self {
        self.beta_features = Some(features);
        self
    }

    /// Configure retry behavior for rate limit and overload errors.
    ///
    /// By default, retries are enabled with exponential backoff. Use this method
    /// to customize retry behavior for high-parallelism scenarios or disable retries.
    ///
    /// # Examples
    ///
    /// Custom retry configuration for high parallelism (20+ parallel workers):
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use appam::llm::LlmProvider;
    /// # use appam::llm::anthropic::RetryConfig;
    /// let agent = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::Anthropic)
    ///     .retry(RetryConfig {
    ///         max_retries: 8,              // More attempts
    ///         initial_backoff_ms: 5000,    // Start with 5s
    ///         max_backoff_ms: 120000,      // Cap at 2min
    ///         backoff_multiplier: 2.0,
    ///         jitter: true,
    ///     })
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    ///
    /// Disable retries:
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use appam::llm::LlmProvider;
    /// let agent = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::Anthropic)
    ///     .disable_retry()
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn retry(mut self, config: crate::llm::anthropic::RetryConfig) -> Self {
        self.retry = Some(config);
        self
    }

    /// Disable automatic retry for rate limit errors.
    ///
    /// By default, retries are enabled. Use this to disable them completely.
    pub fn disable_retry(mut self) -> Self {
        // Setting to None will prevent retry from being applied
        self.retry = Some(crate::llm::anthropic::RetryConfig {
            max_retries: 0,
            initial_backoff_ms: 0,
            max_backoff_ms: 0,
            backoff_multiplier: 1.0,
            jitter: false,
        });
        self
    }

    /// Configure global rate limiting for Anthropic API requests.
    ///
    /// Rate limiting prevents rate limit errors by coordinating requests across
    /// all parallel workers. Highly recommended for high-parallelism scenarios
    /// (15+ workers) where multiple agents compete for the same org-wide rate limit.
    ///
    /// # Examples
    ///
    /// Enable rate limiting for high parallelism:
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use appam::llm::LlmProvider;
    /// # use appam::llm::anthropic::RateLimiterConfig;
    /// let agent = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::Anthropic)
    ///     .rate_limiter(RateLimiterConfig {
    ///         enabled: true,
    ///         tokens_per_minute: 1_800_000,  // 90% of 2M limit
    ///         ..Default::default()
    ///     })
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    ///
    /// Quick enable with defaults:
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use appam::llm::LlmProvider;
    /// # use appam::llm::anthropic::RateLimiterConfig;
    /// let agent = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::Anthropic)
    ///     .enable_rate_limiter()
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn rate_limiter(mut self, config: crate::llm::anthropic::RateLimiterConfig) -> Self {
        self.rate_limiter = Some(config);
        self
    }

    /// Enable global rate limiting with default settings.
    ///
    /// Shorthand for `.rate_limiter(RateLimiterConfig { enabled: true, ..Default::default() })`.
    /// Uses conservative defaults: 1.8M tokens/min, 250K tokens/request.
    pub fn enable_rate_limiter(mut self) -> Self {
        self.rate_limiter = Some(crate::llm::anthropic::RateLimiterConfig {
            enabled: true,
            ..Default::default()
        });
        self
    }

    // ====================================================================
    // Reasoning configuration methods (provider-agnostic)
    // ====================================================================

    /// Set provider-specific reasoning configuration.
    ///
    /// Accepts either OpenAI or OpenRouter reasoning configurations wrapped in
    /// the `ReasoningProvider` enum.
    ///
    /// # Examples
    ///
    /// OpenAI reasoning:
    /// ```no_run
    /// # use appam::agent::{AgentBuilder, ReasoningProvider};
    /// # use appam::llm::LlmProvider;
    /// # use appam::llm::openai::ReasoningConfig;
    /// let agent = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::OpenAI)
    ///     .reasoning(ReasoningProvider::OpenAI(
    ///         ReasoningConfig::high_effort()
    ///     ))
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    ///
    /// OpenRouter reasoning:
    /// ```no_run
    /// # use appam::agent::{AgentBuilder, ReasoningProvider};
    /// # use appam::llm::LlmProvider;
    /// # use appam::llm::openrouter::ReasoningConfig;
    /// let agent = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::OpenRouterResponses)
    ///     .reasoning(ReasoningProvider::OpenRouter(
    ///         ReasoningConfig::high_effort(32000)
    ///     ))
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn reasoning(mut self, config: ReasoningProvider) -> Self {
        self.reasoning = Some(config);
        self
    }

    /// Set OpenAI-specific reasoning configuration (convenience method).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use appam::llm::LlmProvider;
    /// # use appam::llm::openai::ReasoningConfig;
    /// let agent = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::OpenAI)
    ///     .openai_reasoning(ReasoningConfig::high_effort())
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn openai_reasoning(mut self, config: crate::llm::openai::ReasoningConfig) -> Self {
        self.reasoning = Some(ReasoningProvider::OpenAI(config));
        self
    }

    /// Set OpenAI text verbosity level.
    ///
    /// Controls the verbosity of the model's text responses.
    /// Lower values result in more concise responses, while higher values result in more detailed responses.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use appam::llm::LlmProvider;
    /// # use appam::llm::openai::TextVerbosity;
    /// let agent = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::OpenAI)
    ///     .openai_text_verbosity(TextVerbosity::High)
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn openai_text_verbosity(mut self, verbosity: crate::llm::openai::TextVerbosity) -> Self {
        self.openai_text_verbosity = Some(verbosity);
        self
    }

    /// Set the canonical OpenAI model identifier used for pricing/accounting.
    pub fn openai_pricing_model(mut self, model: impl Into<String>) -> Self {
        self.openai_pricing_model = Some(model.into());
        self
    }

    /// Set the canonical Anthropic model identifier used for pricing/accounting.
    ///
    /// This is intended for transports such as Azure-hosted Anthropic where
    /// the request-facing deployment name may differ from the public model slug
    /// used by pricing tables.
    pub fn anthropic_pricing_model(mut self, model: impl Into<String>) -> Self {
        self.anthropic_pricing_model = Some(model.into());
        self
    }

    /// Set OpenRouter-specific reasoning configuration (convenience method).
    ///
    /// Works for both Completions and Responses APIs.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use appam::llm::LlmProvider;
    /// # use appam::llm::openrouter::ReasoningConfig;
    /// let agent = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::OpenRouterCompletions)
    ///     .openrouter_reasoning(ReasoningConfig::high_effort(32000))
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn openrouter_reasoning(
        mut self,
        config: crate::llm::openrouter::config::ReasoningConfig,
    ) -> Self {
        self.reasoning = Some(ReasoningProvider::OpenRouter(config));
        self
    }

    // ====================================================================
    // OpenRouter-specific configuration methods
    // ====================================================================

    /// Set OpenAI API key override.
    ///
    /// Overrides the API key from environment variables or config files.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use appam::llm::LlmProvider;
    /// let agent = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::OpenAI)
    ///     .openai_api_key("sk-...")
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn openai_api_key(mut self, key: impl Into<String>) -> Self {
        self.openai_api_key = Some(key.into());
        self
    }

    /// Set an explicit OpenAI Codex access token override.
    ///
    /// This bypasses auth-cache lookup for the Codex provider and is intended
    /// for callers that already manage ChatGPT OAuth credentials themselves.
    pub fn openai_codex_access_token(mut self, token: impl Into<String>) -> Self {
        self.openai_codex_access_token = Some(token.into());
        self
    }

    /// Set Vertex API key override.
    ///
    /// This key is appended as the `key` query parameter for Vertex requests
    /// unless an explicit bearer token is configured.
    pub fn vertex_api_key(mut self, key: impl Into<String>) -> Self {
        self.vertex_api_key = Some(key.into());
        self
    }

    /// Set OpenAI service tier for request prioritization.
    ///
    /// Service tiers control request routing and queueing:
    /// - `Auto`: Default routing based on account settings
    /// - `Default`: Standard routing for general use
    /// - `Scale`: High-throughput workloads with increased concurrency limits
    /// - `Flex`: Cost-optimized with flexible latency
    /// - `Priority`: Lowest-latency routing for time-sensitive requests
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use appam::llm::LlmProvider;
    /// # use appam::llm::openai::ServiceTier;
    /// let agent = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::OpenAI)
    ///     .model("gpt-5-codex")
    ///     .openai_service_tier(ServiceTier::Scale)
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn openai_service_tier(mut self, tier: crate::llm::openai::ServiceTier) -> Self {
        self.openai_service_tier = Some(tier);
        self
    }

    /// Set provider routing preferences (Completions API only).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use appam::llm::LlmProvider;
    /// # use appam::llm::openrouter::{ProviderPreferences, DataCollection};
    /// let agent = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::OpenRouterCompletions)
    ///     .openrouter_provider_routing(ProviderPreferences {
    ///         order: Some(vec!["anthropic".to_string()]),
    ///         data_collection: Some(DataCollection::Deny),
    ///         zdr: Some(true),
    ///         ..Default::default()
    ///     })
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn openrouter_provider_routing(
        mut self,
        prefs: crate::llm::openrouter::config::ProviderPreferences,
    ) -> Self {
        self.provider_preferences = Some(prefs);
        self
    }

    /// Set OpenRouter prompt transforms (Completions API only).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use appam::llm::LlmProvider;
    /// let agent = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::OpenRouterCompletions)
    ///     .openrouter_transforms(vec!["middleware".to_string()])
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn openrouter_transforms(mut self, transforms: Vec<String>) -> Self {
        self.openrouter_transforms = Some(transforms);
        self
    }

    /// Set fallback models for OpenRouter (Completions API only).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use appam::llm::LlmProvider;
    /// let agent = AgentBuilder::new("agent")
    ///     .provider(LlmProvider::OpenRouterCompletions)
    ///     .model("anthropic/claude-sonnet-4-5")
    ///     .openrouter_models(vec![
    ///         "anthropic/claude-sonnet-4-5".to_string(),
    ///         "openai/gpt-4o".to_string(),
    ///     ])
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn openrouter_models(mut self, models: Vec<String>) -> Self {
        self.openrouter_models = Some(models);
        self
    }

    /// Set maximum tokens to generate.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// let agent = AgentBuilder::new("agent")
    ///     .max_tokens(8192)
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn max_tokens(mut self, max_tokens: u32) -> Self {
        self.max_tokens = Some(max_tokens);
        self
    }

    /// Set temperature for sampling (0.0-1.0).
    ///
    /// Note: Incompatible with Anthropic extended thinking.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// let agent = AgentBuilder::new("agent")
    ///     .temperature(0.7)
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn temperature(mut self, temperature: f32) -> Self {
        self.temperature = Some(temperature);
        self
    }

    /// Set top-p nucleus sampling (0.0-1.0).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// let agent = AgentBuilder::new("agent")
    ///     .top_p(0.9)
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn top_p(mut self, top_p: f32) -> Self {
        self.top_p = Some(top_p);
        self
    }

    /// Set top-k sampling.
    ///
    /// Note: Incompatible with Anthropic extended thinking.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// let agent = AgentBuilder::new("agent")
    ///     .top_k(40)
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn top_k(mut self, top_k: u32) -> Self {
        self.top_k = Some(top_k);
        self
    }

    /// Set custom stop sequences.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// let agent = AgentBuilder::new("agent")
    ///     .stop_sequences(vec!["END".to_string(), "STOP".to_string()])
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn stop_sequences(mut self, sequences: Vec<String>) -> Self {
        self.stop_sequences = Some(sequences);
        self
    }

    // ============================================================================
    // Logging Configuration
    // ============================================================================

    /// Set the logs directory.
    ///
    /// All log files and trace files will be written to this directory.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// let agent = AgentBuilder::new("agent")
    ///     .logs_dir("my_logs")
    ///     .system_prompt("You are helpful.")
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn logs_dir(mut self, path: impl Into<std::path::PathBuf>) -> Self {
        self.logs_dir = Some(path.into());
        self
    }

    /// Set the log level.
    ///
    /// Valid levels: "trace", "debug", "info", "warn", "error"
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// let agent = AgentBuilder::new("agent")
    ///     .log_level("debug")
    ///     .system_prompt("You are helpful.")
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn log_level(mut self, level: impl Into<String>) -> Self {
        self.log_level = Some(level.into());
        self
    }

    /// Set the log file format.
    ///
    /// Determines how logs are written to disk.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use appam::config::LogFormat;
    /// let agent = AgentBuilder::new("agent")
    ///     .log_format(LogFormat::Json)  // or LogFormat::Plain, LogFormat::Both
    ///     .system_prompt("You are helpful.")
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn log_format(mut self, format: crate::config::LogFormat) -> Self {
        self.log_format = Some(format);
        self
    }

    /// Enable session trace files with default detailed format.
    ///
    /// Traces capture complete conversation flow including reasoning and tool calls.
    /// This enables agent traces (session-*.jsonl and session-*.json files).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// let agent = AgentBuilder::new("agent")
    ///     .enable_traces()  // Simple and clear!
    ///     .system_prompt("You are helpful.")
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn enable_traces(mut self) -> Self {
        self.enable_traces = Some(true);
        self
    }

    /// Disable session trace files.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// let agent = AgentBuilder::new("agent")
    ///     .disable_traces()
    ///     .system_prompt("You are helpful.")
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn disable_traces(mut self) -> Self {
        self.enable_traces = Some(false);
        self
    }

    /// Set the trace file detail level.
    ///
    /// - `TraceFormat::Compact`: Essential information only
    /// - `TraceFormat::Detailed`: Full details including reasoning (default)
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use appam::config::TraceFormat;
    /// let agent = AgentBuilder::new("agent")
    ///     .enable_traces()
    ///     .trace_format(TraceFormat::Compact)
    ///     .system_prompt("You are helpful.")
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn trace_format(mut self, format: crate::config::TraceFormat) -> Self {
        self.trace_format = Some(format);
        self
    }

    // ============================================================================
    // History Configuration
    // ============================================================================

    /// Enable session history persistence with sensible defaults.
    ///
    /// Sessions will be saved to `data/sessions.db` with auto-save enabled.
    /// This is a convenience method that sets:
    /// - `history_enabled = true`
    /// - `history_db_path = "data/sessions.db"` (if not already set)
    /// - `history_auto_save = true` (if not already set)
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// let agent = AgentBuilder::new("agent")
    ///     .enable_history()  // Simple! Uses good defaults
    ///     .system_prompt("You are helpful.")
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn enable_history(mut self) -> Self {
        self.history_enabled = Some(true);
        // Set sensible defaults if not already configured
        if self.history_db_path.is_none() {
            self.history_db_path = Some("data/sessions.db".into());
        }
        if self.history_auto_save.is_none() {
            self.history_auto_save = Some(true);
        }
        self
    }

    /// Disable session history persistence.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// let agent = AgentBuilder::new("agent")
    ///     .disable_history()
    ///     .system_prompt("You are helpful.")
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn disable_history(mut self) -> Self {
        self.history_enabled = Some(false);
        self
    }

    /// Set the session history database path.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// let agent = AgentBuilder::new("agent")
    ///     .enable_history()
    ///     .history_db_path("my_data/sessions.db")
    ///     .system_prompt("You are helpful.")
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn history_db_path(mut self, path: impl Into<std::path::PathBuf>) -> Self {
        self.history_db_path = Some(path.into());
        self
    }

    /// Enable or disable automatic session saving.
    ///
    /// When enabled, sessions are automatically saved to the database after completion.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// let agent = AgentBuilder::new("agent")
    ///     .enable_history()
    ///     .auto_save_sessions(true)
    ///     .system_prompt("You are helpful.")
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn auto_save_sessions(mut self, auto_save: bool) -> Self {
        self.history_auto_save = Some(auto_save);
        self
    }

    // ============================================================================
    // Session Continuation Configuration
    // ============================================================================

    /// Require specific tools to be called before session completion.
    ///
    /// When set, the agent will automatically inject a continuation message if
    /// the session ends without calling any of the specified tools. This prevents
    /// premature session termination and ensures analysis is properly completed.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use std::sync::Arc;
    /// # use appam::tools::Tool;
    /// # struct CompletionTool;
    /// # impl Tool for CompletionTool {
    /// #     fn name(&self) -> &str { "completion_tool" }
    /// #     fn spec(&self) -> anyhow::Result<appam::llm::ToolSpec> { todo!() }
    /// #     fn execute(&self, _: serde_json::Value) -> anyhow::Result<serde_json::Value> { todo!() }
    /// # }
    /// let agent = AgentBuilder::new("agent")
    ///     .system_prompt("You are a helpful assistant.")
    ///     .require_completion_tools(vec![Arc::new(CompletionTool)])
    ///     .continuation_message("Please call a completion tool to finish.")
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn require_completion_tools(mut self, tools: Vec<Arc<dyn Tool>>) -> Self {
        self.required_completion_tools = tools;
        self
    }

    /// Set the maximum number of continuation attempts.
    ///
    /// Defaults to 2 if not specified. This prevents infinite loops by limiting
    /// how many times the agent will inject continuation messages.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use std::sync::Arc;
    /// # use appam::tools::Tool;
    /// # struct CompletionTool;
    /// # impl Tool for CompletionTool {
    /// #     fn name(&self) -> &str { "completion_tool" }
    /// #     fn spec(&self) -> anyhow::Result<appam::llm::ToolSpec> { todo!() }
    /// #     fn execute(&self, _: serde_json::Value) -> anyhow::Result<serde_json::Value> { todo!() }
    /// # }
    /// let agent = AgentBuilder::new("agent")
    ///     .system_prompt("You are helpful.")
    ///     .require_completion_tools(vec![Arc::new(CompletionTool)])
    ///     .max_continuations(3)  // Allow up to 3 continuation attempts
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn max_continuations(mut self, count: usize) -> Self {
        self.max_continuations = count;
        self
    }

    /// Set a custom continuation message.
    ///
    /// This message is injected when the session ends without calling required
    /// completion tools. If not set, a default generic message is used.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use std::sync::Arc;
    /// # use appam::tools::Tool;
    /// # struct CompletionTool;
    /// # impl Tool for CompletionTool {
    /// #     fn name(&self) -> &str { "completion_tool" }
    /// #     fn spec(&self) -> anyhow::Result<appam::llm::ToolSpec> { todo!() }
    /// #     fn execute(&self, _: serde_json::Value) -> anyhow::Result<serde_json::Value> { todo!() }
    /// # }
    /// let agent = AgentBuilder::new("agent")
    ///     .system_prompt("You are helpful.")
    ///     .require_completion_tools(vec![Arc::new(CompletionTool)])
    ///     .continuation_message("Continue analysis. Call a completion tool to finish this session.")
    ///     .build()?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn continuation_message(mut self, message: impl Into<String>) -> Self {
        self.continuation_message = Some(message.into());
        self
    }

    /// Set the system prompt inline.
    ///
    /// Use this for short prompts or dynamically generated prompts.
    /// For file-based prompts, use `system_prompt_file()` instead.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// let builder = AgentBuilder::new("agent")
    ///     .system_prompt("You are a helpful AI assistant.");
    /// ```
    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.system_prompt = Some(prompt.into());
        self.system_prompt_file = None; // Clear file if set
        self
    }

    /// Load the system prompt from a file.
    ///
    /// The file will be read during `build()`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// let builder = AgentBuilder::new("agent")
    ///     .system_prompt_file("prompts/assistant.txt");
    /// ```
    pub fn system_prompt_file(mut self, path: impl AsRef<Path>) -> Self {
        self.system_prompt_file = Some(path.as_ref().to_path_buf());
        self.system_prompt = None; // Clear inline if set
        self
    }

    /// Add a single tool to the agent.
    ///
    /// Tools can be added multiple times to register several tools.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use std::sync::Arc;
    /// # use appam::tools::Tool;
    /// # struct MyTool;
    /// # impl Tool for MyTool {
    /// #     fn name(&self) -> &str { "my_tool" }
    /// #     fn spec(&self) -> anyhow::Result<appam::llm::ToolSpec> { todo!() }
    /// #     fn execute(&self, _: serde_json::Value) -> anyhow::Result<serde_json::Value> { todo!() }
    /// # }
    /// let builder = AgentBuilder::new("agent")
    ///     .system_prompt("You are an assistant.")
    ///     .with_tool(Arc::new(MyTool));
    /// ```
    pub fn with_tool(mut self, tool: Arc<dyn Tool>) -> Self {
        self.tools.push(tool);
        self
    }

    /// Add a single async/context-aware tool to the agent.
    pub fn with_async_tool(mut self, tool: Arc<dyn AsyncTool>) -> Self {
        self.async_tools.push(tool);
        self
    }

    /// Add multiple tools at once.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use std::sync::Arc;
    /// # use appam::tools::Tool;
    /// # struct Tool1;
    /// # struct Tool2;
    /// # impl Tool for Tool1 {
    /// #     fn name(&self) -> &str { "tool1" }
    /// #     fn spec(&self) -> anyhow::Result<appam::llm::ToolSpec> { todo!() }
    /// #     fn execute(&self, _: serde_json::Value) -> anyhow::Result<serde_json::Value> { todo!() }
    /// # }
    /// # impl Tool for Tool2 {
    /// #     fn name(&self) -> &str { "tool2" }
    /// #     fn spec(&self) -> anyhow::Result<appam::llm::ToolSpec> { todo!() }
    /// #     fn execute(&self, _: serde_json::Value) -> anyhow::Result<serde_json::Value> { todo!() }
    /// # }
    /// let builder = AgentBuilder::new("agent")
    ///     .system_prompt("You are an assistant.")
    ///     .with_tools(vec![Arc::new(Tool1), Arc::new(Tool2)]);
    /// ```
    pub fn with_tools(mut self, tools: Vec<Arc<dyn Tool>>) -> Self {
        self.tools.extend(tools);
        self
    }

    /// Add multiple async/context-aware tools at once.
    pub fn with_async_tools(mut self, tools: Vec<Arc<dyn AsyncTool>>) -> Self {
        self.async_tools.extend(tools);
        self
    }

    /// Provide a custom tool registry.
    ///
    /// If not provided, a new empty registry will be created and tools
    /// added via `with_tool()` will be registered to it.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use appam::tools::ToolRegistry;
    /// # use std::sync::Arc;
    /// let registry = Arc::new(ToolRegistry::new());
    /// // Pre-register tools in the registry...
    ///
    /// let builder = AgentBuilder::new("agent")
    ///     .system_prompt("You are an assistant.")
    ///     .with_registry(registry);
    /// ```
    pub fn with_registry(mut self, registry: Arc<ToolRegistry>) -> Self {
        self.registry = Some(registry);
        self
    }

    fn ensure_registry(&mut self) -> Arc<ToolRegistry> {
        Arc::clone(
            self.registry
                .get_or_insert_with(|| Arc::new(ToolRegistry::new())),
        )
    }

    /// Register an app-scoped managed state value.
    pub fn manage<T>(mut self, state: T) -> Self
    where
        T: Send + Sync + 'static,
    {
        self.ensure_registry().manage(state);
        self
    }

    /// Register a lazily initialized session-scoped state type using `Default`.
    pub fn session_state<T>(mut self) -> Self
    where
        T: Default + Send + Sync + 'static,
    {
        self.ensure_registry()
            .session_state_with::<T, _>(T::default);
        self
    }

    /// Register a lazily initialized session-scoped state type with a custom initializer.
    pub fn session_state_with<T, F>(mut self, init: F) -> Self
    where
        T: Send + Sync + 'static,
        F: Fn() -> T + Send + Sync + 'static,
    {
        self.ensure_registry().session_state_with::<T, F>(init);
        self
    }

    /// Enable provider-side tool batching and runtime parallel execution.
    ///
    /// The runtime still executes sequentially unless a returned batch contains
    /// only `ParallelSafe` tools.
    pub fn enable_parallel_tool_calls(mut self, max_concurrency: usize) -> Self {
        self.provider_parallel_tool_calls = true;
        self.max_concurrent_tool_executions = max_concurrency.max(1);
        self
    }

    /// Build the agent from the configured builder.
    ///
    /// This validates the configuration and constructs a `RuntimeAgent`.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No system prompt is provided (neither inline nor file)
    /// - System prompt file cannot be read
    /// - Configuration is otherwise invalid
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use appam::agent::AgentBuilder;
    /// # use anyhow::Result;
    /// # fn main() -> Result<()> {
    /// let agent = AgentBuilder::new("my-agent")
    ///     .model("openai/gpt-5")
    ///     .system_prompt("You are a helpful assistant.")
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn build(self) -> Result<RuntimeAgent> {
        // Validate and load system prompt
        let system_prompt = if let Some(prompt) = self.system_prompt {
            prompt
        } else if let Some(path) = self.system_prompt_file {
            std::fs::read_to_string(&path)
                .with_context(|| format!("Failed to read system prompt: {}", path.display()))?
        } else {
            anyhow::bail!(
                "System prompt must be provided via system_prompt() or system_prompt_file()"
            );
        };

        // Create or use provided registry
        let registry = self
            .registry
            .unwrap_or_else(|| Arc::new(ToolRegistry::new()));

        // Register tools
        for tool in self.tools {
            registry.register(tool);
        }

        for tool in self.async_tools {
            registry.register_async(tool);
        }

        // Register required completion tools (they also need to be in the registry)
        for tool in &self.required_completion_tools {
            registry.register(Arc::clone(tool));
        }

        // Extract tool names for continuation checking
        let required_tool_names: Option<Vec<String>> = if !self.required_completion_tools.is_empty()
        {
            Some(
                self.required_completion_tools
                    .iter()
                    .map(|t| t.name().to_string())
                    .collect(),
            )
        } else {
            None
        };

        // Build RuntimeAgent with all configuration
        let agent = RuntimeAgent::with_config(
            &self.name,
            system_prompt,
            registry,
            self.provider,
            self.model,
            self.anthropic_api_key,
            self.openrouter_api_key,
            self.openai_api_key,
            self.openai_codex_access_token,
            self.vertex_api_key,
            self.openai_service_tier,
            self.openai_text_verbosity,
            self.openai_pricing_model,
            self.anthropic_pricing_model,
            self.thinking,
            self.caching,
            self.tool_choice,
            self.effort,
            self.beta_features,
            self.retry,
            self.rate_limiter,
            self.reasoning,
            self.provider_preferences,
            self.openrouter_transforms,
            self.openrouter_models,
            self.max_tokens,
            self.temperature,
            self.top_p,
            self.top_k,
            self.stop_sequences,
            self.logs_dir,
            self.log_level,
            self.log_format,
            self.enable_traces,
            self.trace_format,
            self.history_enabled,
            self.history_db_path,
            self.history_auto_save,
            required_tool_names,
            self.max_continuations,
            self.continuation_message,
            self.provider_parallel_tool_calls,
            self.max_concurrent_tool_executions,
        );

        Ok(agent)
    }

    /// Build the agent with a streaming channel.
    ///
    /// Returns both the agent and a receiver for stream events. Events are sent
    /// to the receiver as the agent executes, allowing async consumption of
    /// the stream.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// # use appam::agent::AgentBuilder;
    /// # use anyhow::Result;
    /// # async fn example() -> Result<()> {
    /// let (agent, mut stream) = AgentBuilder::new("my-agent")
    ///     .system_prompt("You are helpful.")
    ///     .build_with_stream()?;
    ///
    /// // Spawn task to handle events
    /// tokio::spawn(async move {
    ///     while let Some(event) = stream.recv().await {
    ///         println!("Event: {:?}", event);
    ///     }
    /// });
    ///
    /// agent.run("Hello!").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn build_with_stream(
        self,
    ) -> Result<(
        RuntimeAgent,
        tokio::sync::mpsc::UnboundedReceiver<super::streaming::StreamEvent>,
    )> {
        let agent = self.build()?;
        let (_tx, rx) = tokio::sync::mpsc::unbounded_channel();

        // Note: The receiver is returned for the user to consume.
        // The agent will use ConsoleConsumer by default when calling run().
        // To stream to this channel, use run_streaming() with ChannelConsumer.

        Ok((agent, rx))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::Agent;
    use crate::llm::ToolSpec;
    use serde_json::json;
    use std::io::Write;
    use tempfile::NamedTempFile;

    struct MockTool {
        name: String,
    }

    impl Tool for MockTool {
        fn name(&self) -> &str {
            &self.name
        }

        fn spec(&self) -> Result<ToolSpec> {
            Ok(serde_json::from_value(json!({
                "type": "function",
                "name": self.name,
                "description": "Mock tool",
                "parameters": {
                    "type": "object",
                    "properties": {}
                }
            }))?)
        }

        fn execute(&self, _args: serde_json::Value) -> Result<serde_json::Value> {
            Ok(json!({"success": true}))
        }
    }

    #[test]
    fn test_builder_basic() {
        let agent = AgentBuilder::new("test-agent")
            .system_prompt("Test prompt")
            .build()
            .unwrap();

        assert_eq!(agent.name(), "test-agent");
    }

    #[test]
    fn test_builder_with_model() {
        let agent = AgentBuilder::new("test-agent")
            .model("anthropic/claude-3.5-sonnet")
            .system_prompt("Test prompt")
            .build()
            .unwrap();

        assert_eq!(agent.model(), "anthropic/claude-3.5-sonnet");
    }

    #[test]
    fn test_builder_with_tool() {
        let agent = AgentBuilder::new("test-agent")
            .system_prompt("Test prompt")
            .with_tool(Arc::new(MockTool {
                name: "test_tool".to_string(),
            }))
            .build()
            .unwrap();

        let tools = agent.available_tools().unwrap();
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0].name, "test_tool");
    }

    #[test]
    fn test_builder_with_multiple_tools() {
        let agent = AgentBuilder::new("test-agent")
            .system_prompt("Test prompt")
            .with_tools(vec![
                Arc::new(MockTool {
                    name: "tool1".to_string(),
                }),
                Arc::new(MockTool {
                    name: "tool2".to_string(),
                }),
            ])
            .build()
            .unwrap();

        let tools = agent.available_tools().unwrap();
        assert_eq!(tools.len(), 2);
    }

    #[test]
    fn test_builder_with_prompt_file() {
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(b"File-based prompt").unwrap();
        file.flush().unwrap();

        let agent = AgentBuilder::new("test-agent")
            .system_prompt_file(file.path())
            .build()
            .unwrap();

        use super::super::Agent;
        assert_eq!(agent.system_prompt().unwrap(), "File-based prompt");
    }

    #[test]
    fn test_builder_missing_prompt() {
        let result = AgentBuilder::new("test-agent").build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("System prompt"));
    }

    #[test]
    fn test_builder_with_custom_registry() {
        let registry = Arc::new(ToolRegistry::new());
        registry.register(Arc::new(MockTool {
            name: "pre_registered".to_string(),
        }));

        let agent = AgentBuilder::new("test-agent")
            .system_prompt("Test prompt")
            .with_registry(registry.clone())
            .with_tool(Arc::new(MockTool {
                name: "added_later".to_string(),
            }))
            .build()
            .unwrap();

        let tools = agent.available_tools().unwrap();
        assert_eq!(tools.len(), 2);
    }
}