edgecrab-core 0.1.0

Agent core: conversation loop, prompt builder, context compression, model routing
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
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
//! # Agent — core entry point for conversation execution
//!
//! WHY a builder: The Agent needs ~10 dependencies injected (provider,
//! tools, state DB, callbacks, config). A builder prevents 10-argument
//! constructors and makes optional dependencies explicit.
//!
//! ```text
//!   AgentBuilder::new("model")
//!       .provider(provider)
//!       .tools(registry)
//!       .state_db(db)
//!       .build()? ──→ Agent
//!                      │
//!                      ├── .chat("hi")        → simple interface
//!                      └── .run_conversation() → full interface
//! ```

use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};

use tokio::sync::RwLock;
use tokio_util::sync::CancellationToken;

use edgecrab_state::SessionDb;
use edgecrab_tools::ProcessTable;
use edgecrab_tools::TodoStore;
use edgecrab_tools::registry::{GatewaySender, ToolRegistry};
use edgecrab_types::{AgentError, ApiMode, Cost, Message, Platform, Role, Usage};
use edgequake_llm::LLMProvider;

use crate::config::AppConfig;

// ─── Agent ────────────────────────────────────────────────────────────

pub struct Agent {
    /// WHY RwLock on config: Model hot-swap (/model command) updates the
    /// model name at runtime. RwLock allows concurrent reads during the
    /// conversation loop while permitting rare writes on model switch.
    pub(crate) config: RwLock<AgentConfig>,
    /// WHY RwLock on provider: The /model command swaps the LLM provider
    /// at runtime. The conversation loop clones the Arc at loop start,
    /// so in-flight conversations aren't affected by a swap.
    pub(crate) provider: RwLock<Arc<dyn LLMProvider>>,
    #[allow(dead_code)] // Used in Phase 1.6 conversation loop
    pub(crate) state_db: Option<Arc<SessionDb>>,
    pub(crate) tool_registry: Option<Arc<ToolRegistry>>,
    /// Gateway-backed outbound sender for `send_message`.
    ///
    /// None in plain CLI / cron sessions. Set by the messaging gateway runtime
    /// so tool execution can deliver to external platforms without duplicating
    /// transport logic inside the agent loop.
    pub(crate) gateway_sender: RwLock<Option<Arc<dyn GatewaySender>>>,
    /// Shared process table for background-process management tools.
    /// WHY on Agent: All tool invocations in the same session share the
    /// same process namespace — Agent lifetime == session lifetime.
    pub(crate) process_table: Arc<ProcessTable>,
    pub(crate) session: RwLock<SessionState>,
    pub(crate) budget: Arc<IterationBudget>,
    /// Cancel token is wrapped in a Mutex so it can be RESET before each new
    /// conversation turn. CancellationToken is a one-way latch — once cancelled
    /// it cannot be un-cancelled. By replacing it with a fresh token at the
    /// start of execute_loop we ensure Ctrl+C only stops the current turn, not
    /// all future turns.
    pub(crate) cancel: std::sync::Mutex<CancellationToken>,
    /// Dedicated cancel token for the process-table GC task.
    ///
    /// WHY separate from `cancel`: `cancel` is reset on every new conversation
    /// turn (see execute_loop) so it can't drive a long-lived background task.
    /// `gc_cancel` lives for the full Agent lifetime and is cancelled via
    /// `Drop` so the GC stops when the Agent is dropped.  Mirrors the cleanup
    /// semantics of hermes-agent's `FINISHED_TTL_SECONDS` periodic cleanup.
    pub(crate) gc_cancel: CancellationToken,
    /// Per-session task list — survives context compression.
    ///
    /// WHY on Agent: The Agent lifetime == session lifetime. Placing the store
    /// here mirrors hermes-agent's `self._todo_store` on the `AIAgent` class.
    /// After each compression `format_for_injection()` re-injects active items
    /// so the model never loses its plan across context-window boundaries.
    pub(crate) todo_store: Arc<edgecrab_tools::TodoStore>,
}

/// Options for cloning an agent into a fresh isolated session.
#[derive(Debug, Clone, Default)]
pub struct IsolatedAgentOptions {
    /// Optional fixed session identifier for the child session.
    pub session_id: Option<String>,
    /// Optional platform override for the child session.
    pub platform: Option<Platform>,
    /// Optional quiet-mode override.
    pub quiet_mode: Option<bool>,
    /// Optional origin chat override for gateway-created isolated sessions.
    pub origin_chat: Option<(String, String)>,
}

/// Immutable per-agent configuration (subset of AppConfig relevant to the loop).
#[derive(Debug, Clone)]
pub struct AgentConfig {
    pub model: String,
    pub max_iterations: u32,
    pub enabled_toolsets: Vec<String>,
    pub disabled_toolsets: Vec<String>,
    pub streaming: bool,
    pub temperature: Option<f32>,
    pub platform: Platform,
    pub api_mode: ApiMode,
    pub session_id: Option<String>,
    pub quiet_mode: bool,
    pub save_trajectories: bool,
    pub skip_context_files: bool,
    pub skip_memory: bool,
    pub reasoning_effort: Option<String>,
    /// Optional persona/personality instruction appended to the system prompt.
    /// Resolved from `config.display.personality` via `resolve_personality()`.
    pub personality_addon: Option<String>,
    /// Model config for routing (base_url, api_key_env, smart routing).
    pub model_config: crate::config::ModelConfig,
    /// Skills config — disabled skills, platform-specific disabled.
    pub skills_config: crate::config::SkillsConfig,
    /// Delegation runtime controls mirrored from AppConfig.delegation.
    pub delegation_enabled: bool,
    pub delegation_model: Option<String>,
    pub delegation_provider: Option<String>,
    pub delegation_max_subagents: u32,
    pub delegation_max_iterations: u32,
    /// Origin of the current session — (platform_name, chat_id).
    ///
    /// Set by the gateway when a message arrives from a real chat
    /// (Telegram, WhatsApp, Discord, etc.).  Passed into every `ToolContext`
    /// so that `manage_cron_jobs(action='create', deliver='origin')` can
    /// record the correct delivery target without the LLM needing to know it.
    /// None in CLI / cron / test sessions.
    pub origin_chat: Option<(String, String)>,
    /// Browser automation config (recording, timeouts).
    pub browser: crate::config::BrowserConfig,
    /// Whether automatic checkpoints are enabled.
    pub checkpoints_enabled: bool,
    /// Maximum checkpoints to retain per working directory.
    pub checkpoints_max_snapshots: u32,
    /// Active terminal backend and backend-specific configuration.
    pub terminal_backend: edgecrab_tools::tools::backends::BackendKind,
    pub terminal_docker: edgecrab_tools::tools::backends::DockerBackendConfig,
    pub terminal_ssh: edgecrab_tools::tools::backends::SshBackendConfig,
    pub terminal_modal: edgecrab_tools::tools::backends::ModalBackendConfig,
    pub terminal_daytona: edgecrab_tools::tools::backends::DaytonaBackendConfig,
    pub terminal_singularity: edgecrab_tools::tools::backends::SingularityBackendConfig,
    /// Auxiliary side-task routing (vision, compression, other helper calls).
    pub auxiliary: crate::config::AuxiliaryConfig,
    /// Env-var names allowed to pass through the subprocess security blocklist.
    ///
    /// Populated from `terminal.env_passthrough` in config.yaml and applied
    /// to the global registry when the Agent is built.  Skills that declare
    /// `required_environment_variables` also feed the registry at load time.
    pub terminal_env_passthrough: Vec<String>,
    /// Additional file roots trusted by file tools beyond the active workspace.
    pub file_allowed_roots: Vec<std::path::PathBuf>,
    /// Denied prefixes layered over the workspace and allow-root policy.
    pub path_restrictions: Vec<std::path::PathBuf>,
}

impl Default for AgentConfig {
    fn default() -> Self {
        Self {
            model: "anthropic/claude-opus-4.6".into(),
            max_iterations: 90,
            enabled_toolsets: Vec::new(),
            disabled_toolsets: Vec::new(),
            streaming: true,
            temperature: None,
            platform: Platform::Cli,
            api_mode: ApiMode::ChatCompletions,
            session_id: None,
            quiet_mode: false,
            save_trajectories: false,
            skip_context_files: false,
            skip_memory: false,
            reasoning_effort: None,
            personality_addon: None,
            model_config: crate::config::ModelConfig::default(),
            skills_config: crate::config::SkillsConfig::default(),
            delegation_enabled: true,
            delegation_model: None,
            delegation_provider: None,
            delegation_max_subagents: 3,
            delegation_max_iterations: 50,
            origin_chat: None,
            browser: crate::config::BrowserConfig::default(),
            checkpoints_enabled: true,
            checkpoints_max_snapshots: 50,
            terminal_backend: edgecrab_tools::tools::backends::BackendKind::Local,
            terminal_docker: edgecrab_tools::tools::backends::DockerBackendConfig::default(),
            terminal_ssh: edgecrab_tools::tools::backends::SshBackendConfig::default(),
            terminal_modal: edgecrab_tools::tools::backends::ModalBackendConfig::default(),
            terminal_daytona: edgecrab_tools::tools::backends::DaytonaBackendConfig::default(),
            terminal_singularity:
                edgecrab_tools::tools::backends::SingularityBackendConfig::default(),
            auxiliary: crate::config::AuxiliaryConfig::default(),
            terminal_env_passthrough: Vec::new(),
            file_allowed_roots: Vec::new(),
            path_restrictions: Vec::new(),
        }
    }
}

/// Per-session mutable state, protected by RwLock.
#[derive(Default)]
pub struct SessionState {
    /// Unique session identifier — set once at conversation start,
    /// persisted to SQLite at loop end for session search/history.
    pub session_id: Option<String>,
    pub messages: Vec<Message>,
    pub cached_system_prompt: Option<String>,
    pub user_turn_count: u32,
    pub api_call_count: u32,
    pub session_input_tokens: u64,
    pub session_output_tokens: u64,
    pub session_cache_read_tokens: u64,
    pub session_cache_write_tokens: u64,
    pub session_reasoning_tokens: u64,
    pub session_tool_call_count: u32,
}

/// Lock-free iteration budget — prevents runaway tool loops.
///
/// WHY AtomicU32: The budget is checked on every loop iteration and
/// decremented atomically. No mutex contention on the hot path.
pub struct IterationBudget {
    remaining: AtomicU32,
    max: u32,
}

impl IterationBudget {
    pub fn new(max: u32) -> Self {
        Self {
            remaining: AtomicU32::new(max),
            max,
        }
    }

    /// Try to consume one iteration. Returns false when exhausted.
    pub fn try_consume(&self) -> bool {
        // CAS loop: only decrement if remaining > 0.
        loop {
            let current = self.remaining.load(Ordering::Relaxed);
            if current == 0 {
                return false;
            }
            if self
                .remaining
                .compare_exchange_weak(current, current - 1, Ordering::Relaxed, Ordering::Relaxed)
                .is_ok()
            {
                return true;
            }
        }
    }

    pub fn remaining(&self) -> u32 {
        self.remaining.load(Ordering::Relaxed)
    }

    pub fn max(&self) -> u32 {
        self.max
    }

    pub fn used(&self) -> u32 {
        self.max.saturating_sub(self.remaining())
    }

    pub fn reset(&self) {
        self.remaining.store(self.max, Ordering::Relaxed);
    }
}

/// Result of a full conversation run.
#[derive(Debug, Clone)]
pub struct ConversationResult {
    pub final_response: String,
    pub messages: Vec<Message>,
    pub session_id: String,
    pub api_calls: u32,
    pub interrupted: bool,
    /// True when the iteration budget was exhausted before the LLM produced
    /// a final text response. Distinct from `interrupted` (user Ctrl+C).
    pub budget_exhausted: bool,
    pub model: String,
    pub usage: Usage,
    pub cost: Cost,
    /// Per-tool-call error records accumulated across the entire conversation.
    ///
    /// Mirrors hermes-agent's `AgentResult.tool_errors: List[ToolError]`.
    /// Each entry captures the turn number, tool name, arguments, and the
    /// error text — enabling structured observability and RL training without
    /// requiring callers to parse raw message history.
    pub tool_errors: Vec<edgecrab_types::ToolErrorRecord>,
}

// ─── Simple API ───────────────────────────────────────────────────────

impl Agent {
    fn build_runtime_clone(
        config: AgentConfig,
        provider: Arc<dyn LLMProvider>,
        state_db: Option<Arc<SessionDb>>,
        tool_registry: Option<Arc<ToolRegistry>>,
    ) -> Self {
        let budget = Arc::new(IterationBudget::new(config.max_iterations));

        let gc_cancel = CancellationToken::new();
        let process_table = Arc::new(ProcessTable::new());
        process_table.spawn_gc_task(gc_cancel.clone());

        Self {
            config: RwLock::new(config),
            provider: RwLock::new(provider),
            state_db,
            tool_registry,
            gateway_sender: RwLock::new(None),
            process_table,
            session: RwLock::new(SessionState::default()),
            budget,
            cancel: std::sync::Mutex::new(CancellationToken::new()),
            gc_cancel,
            todo_store: Arc::new(TodoStore::new()),
        }
    }

    /// Simple interface — send a message, get a response string.
    pub async fn chat(&self, message: &str) -> Result<String, AgentError> {
        let result = self.run_conversation(message, None, None).await?;
        Ok(result.final_response)
    }

    /// Session-aware interface — run a turn relative to the provided workspace.
    pub async fn chat_in_cwd(&self, message: &str, cwd: &Path) -> Result<String, AgentError> {
        let result = self
            .run_conversation_in_cwd(message, None, None, cwd)
            .await?;
        Ok(result.final_response)
    }

    /// Inject or replace the gateway-backed outbound sender used by `send_message`.
    pub async fn set_gateway_sender(&self, sender: Arc<dyn GatewaySender>) {
        *self.gateway_sender.write().await = Some(sender);
    }

    /// Gateway interface — send a message with origin context (platform + chat_id).
    ///
    /// Unlike `chat()`, this sets the origin so that `manage_cron_jobs` jobs
    /// created in this session will have deliver='origin' route back to the
    /// correct chat automatically.  Also updates `config.platform` so the
    /// system prompt includes the correct platform hints (WhatsApp, Telegram, etc.).
    pub async fn chat_with_origin(
        &self,
        message: &str,
        platform: &str,
        chat_id: &str,
    ) -> Result<String, AgentError> {
        // Set origin_chat and platform for this conversation turn.
        {
            let mut cfg = self.config.write().await;
            cfg.origin_chat = Some((platform.to_string(), chat_id.to_string()));
            cfg.platform = platform_from_str(platform).unwrap_or(cfg.platform);
        }
        let result = self.run_conversation(message, None, None).await?;
        {
            // Clear origin after the turn so it isn't stale for the next message.
            let mut cfg = self.config.write().await;
            cfg.origin_chat = None;
        }
        Ok(result.final_response)
    }

    /// Streaming gateway interface — sets origin context, then streams events.
    ///
    /// Combines the origin-context setup of `chat_with_origin()` with the
    /// progressive streaming of `chat_streaming()`.  This is the method the
    /// gateway dispatch loop should call so that:
    /// 1. `manage_cron_jobs` jobs route back to the originating chat.
    /// 2. The system prompt includes the correct platform hints.
    /// 3. Streamed `Token`, `Reasoning`, `ToolExec`, … events reach the caller.
    pub async fn chat_streaming_with_origin(
        &self,
        message: &str,
        platform: &str,
        chat_id: &str,
        chunk_tx: tokio::sync::mpsc::UnboundedSender<StreamEvent>,
    ) -> Result<(), AgentError> {
        // Set origin and platform — identical to chat_with_origin().
        {
            let mut cfg = self.config.write().await;
            cfg.origin_chat = Some((platform.to_string(), chat_id.to_string()));
            cfg.platform = platform_from_str(platform).unwrap_or(cfg.platform);
        }

        let result = self.chat_streaming(message, chunk_tx).await;

        // Clear origin after the turn regardless of success/failure.
        {
            let mut cfg = self.config.write().await;
            cfg.origin_chat = None;
        }

        result
    }

    /// Streaming interface — sends tokens to `chunk_tx` as they arrive.
    ///
    /// WHY delegate to execute_loop: We want the full ReAct loop (tools,
    /// memory, prompt builder, retries) to remain the single source of truth.
    /// When the provider supports native tool streaming, `execute_loop()` now
    /// emits live token/reasoning events directly. Otherwise we fall back to
    /// streaming the final response in chunks after the synchronous turn ends.
    pub async fn chat_streaming(
        &self,
        message: &str,
        chunk_tx: tokio::sync::mpsc::UnboundedSender<StreamEvent>,
    ) -> Result<(), AgentError> {
        let (streaming_enabled, use_native_streaming) = {
            let config = self.config.read().await;
            let provider = self.provider.read().await;
            let streaming_enabled = config.streaming;
            let use_native_streaming = streaming_enabled && provider.supports_tool_streaming();
            (streaming_enabled, use_native_streaming)
        };

        match self
            .execute_loop(message, None, None, Some(&chunk_tx), None)
            .await
        {
            Ok(result) => {
                // Fallback path: provider doesn't expose live deltas through
                // the full tool loop, so synthesize only what the user asked for:
                // - streaming ON  → chunk the final answer for progressive UX
                // - streaming OFF → send one complete answer at the end
                if !use_native_streaming {
                    if let Some(reasoning) = result
                        .messages
                        .iter()
                        .rev()
                        .find(|msg| msg.role == Role::Assistant)
                        .and_then(|msg| msg.reasoning.clone())
                        .filter(|reasoning| !reasoning.trim().is_empty())
                    {
                        let _ = chunk_tx.send(StreamEvent::Reasoning(reasoning));
                    }

                    if streaming_enabled {
                        for chunk in result.final_response.as_bytes().chunks(50) {
                            let text = String::from_utf8_lossy(chunk).into_owned();
                            let _ = chunk_tx.send(StreamEvent::Token(text));
                        }
                    } else if !result.final_response.is_empty() {
                        let _ = chunk_tx.send(StreamEvent::Token(result.final_response.clone()));
                    }
                }
                let _ = chunk_tx.send(StreamEvent::Done);
                Ok(())
            }
            Err(e) => {
                let _ = chunk_tx.send(StreamEvent::Error(e.to_string()));
                Err(e)
            }
        }
    }

    /// Full conversation interface.
    ///
    /// Delegates to `execute_loop()` (conversation.rs) which implements
    /// the full agent loop with retry, tool dispatch, and cancellation.
    pub async fn run_conversation(
        &self,
        user_message: &str,
        system_message: Option<&str>,
        conversation_history: Option<Vec<Message>>,
    ) -> Result<ConversationResult, AgentError> {
        self.execute_loop(
            user_message,
            system_message,
            conversation_history,
            None,
            None,
        )
        .await
    }

    /// Full conversation interface with an explicit workspace root.
    pub async fn run_conversation_in_cwd(
        &self,
        user_message: &str,
        system_message: Option<&str>,
        conversation_history: Option<Vec<Message>>,
        cwd: &Path,
    ) -> Result<ConversationResult, AgentError> {
        self.execute_loop(
            user_message,
            system_message,
            conversation_history,
            None,
            Some(cwd),
        )
        .await
    }

    /// Clone the agent runtime into a fresh isolated session.
    ///
    /// WHY this exists: `/background` and similar workflows need the current
    /// model, provider, tool configuration, and state DB wiring, but must not
    /// share conversation history, process tables, or cancellation state with
    /// the foreground session.
    pub async fn fork_isolated(&self, options: IsolatedAgentOptions) -> Result<Self, AgentError> {
        let mut config = self.config.read().await.clone();
        let provider = self.provider.read().await.clone();
        let gateway_sender = self.gateway_sender.read().await.clone();

        if let Some(session_id) = options.session_id {
            config.session_id = Some(session_id);
        } else {
            config.session_id = None;
        }
        if let Some(platform) = options.platform {
            config.platform = platform;
        }
        if let Some(quiet_mode) = options.quiet_mode {
            config.quiet_mode = quiet_mode;
        }
        config.origin_chat = options.origin_chat;

        let child = Self::build_runtime_clone(
            config,
            provider,
            self.state_db.clone(),
            self.tool_registry.clone(),
        );
        if let Some(sender) = gateway_sender {
            child.set_gateway_sender(sender).await;
        }
        Ok(child)
    }

    /// Signal the agent to stop at the next iteration boundary.
    pub fn interrupt(&self) {
        self.cancel
            .lock()
            .expect("cancel mutex not poisoned")
            .cancel();
    }

    /// Whether the cancellation token has been triggered.
    pub fn is_cancelled(&self) -> bool {
        self.cancel
            .lock()
            .expect("cancel mutex not poisoned")
            .is_cancelled()
    }

    /// Reset session state for a new conversation.
    pub async fn new_session(&self) {
        // Clear the per-session env passthrough registry so stale skill
        // registrations from the previous session don't leak.  Re-register
        // config-level passthrough entries immediately so they remain
        // available for the new session's very first PersistentShell spawn.
        let passthrough = {
            let cfg = self.config.read().await;
            cfg.terminal_env_passthrough.clone()
        };
        edgecrab_tools::tools::backends::local::clear_env_passthrough();
        if !passthrough.is_empty() {
            edgecrab_tools::tools::backends::local::register_env_passthrough(&passthrough);
        }

        let mut session = self.session.write().await;
        *session = SessionState::default();
        self.budget.reset();
    }

    /// Hot-swap the LLM model and provider at runtime.
    ///
    /// WHY: The `/model` command needs to switch providers without
    /// restarting the CLI. In-flight conversations are not affected
    /// because `execute_loop()` clones the provider Arc at loop start.
    pub async fn swap_model(&self, model: String, provider: Arc<dyn LLMProvider>) {
        {
            let mut cfg = self.config.write().await;
            cfg.model = model;
        }
        {
            let mut prov = self.provider.write().await;
            *prov = provider;
        }
    }

    /// Get the current model name.
    pub async fn model(&self) -> String {
        self.config.read().await.model.clone()
    }

    /// Snapshot of live session stats for `/status`, `/cost`, `/history` commands.
    pub async fn session_snapshot(&self) -> SessionSnapshot {
        let session = self.session.read().await;
        let config = self.config.read().await;
        SessionSnapshot {
            session_id: session.session_id.clone(),
            model: config.model.clone(),
            message_count: session.messages.len(),
            user_turn_count: session.user_turn_count,
            api_call_count: session.api_call_count,
            input_tokens: session.session_input_tokens,
            output_tokens: session.session_output_tokens,
            cache_read_tokens: session.session_cache_read_tokens,
            cache_write_tokens: session.session_cache_write_tokens,
            reasoning_tokens: session.session_reasoning_tokens,
            budget_remaining: self.budget.remaining(),
            budget_max: self.budget.max(),
        }
    }

    /// Get the currently assembled system prompt (if cached).
    pub async fn system_prompt(&self) -> Option<String> {
        self.session.read().await.cached_system_prompt.clone()
    }

    /// Append a note to the cached system prompt.
    ///
    /// Used to inject runtime context (e.g. "browser is now connected to live
    /// Chrome") without consuming a full user→model conversation turn.
    /// The note is appended once; callers should guard for idempotency.
    /// If the system prompt hasn't been built yet it will be set as the full
    /// prompt at first-turn assembly time and this note will be ignored — the
    /// note is silently discarded rather than force-building the prompt early.
    pub async fn append_to_system_prompt(&self, note: &str) {
        let mut session = self.session.write().await;
        if let Some(ref mut prompt) = session.cached_system_prompt {
            prompt.push_str("\n\n");
            prompt.push_str(note);
        }
        // If the system prompt isn't cached yet (no messages sent) we store the
        // note in a pending field so it can be appended at build time.
        // For simplicity we skip that path — callers send /browser connect after
        // the first message, so the prompt is already cached.
    }

    pub async fn invalidate_system_prompt(&self) {
        let mut session = self.session.write().await;
        session.cached_system_prompt = None;
    }

    pub async fn set_personality_addon(&self, addon: Option<String>) {
        {
            let mut config = self.config.write().await;
            config.personality_addon = addon;
        }
        self.invalidate_system_prompt().await;
    }

    /// Inject a synthetic assistant message directly into the conversation history.
    ///
    /// Used after runtime context changes (e.g. `/browser connect`) to make the
    /// model "remember" that its capabilities changed, overriding any prior turns
    /// where it claimed not to have those capabilities.  The injected message is
    /// NOT sent to the LLM — it appears in the history context that the LLM reads
    /// on the NEXT real user turn.
    pub async fn inject_assistant_context(&self, text: &str) {
        let mut session = self.session.write().await;
        session.messages.push(Message::assistant(text));
    }

    /// Get full message history for export.
    pub async fn messages(&self) -> Vec<Message> {
        self.session.read().await.messages.clone()
    }

    /// Remove the last user + assistant turn from history (undo).
    /// Returns the number of messages removed (0 if history is empty).
    pub async fn undo_last_turn(&self) -> usize {
        let mut session = self.session.write().await;
        let mut removed = 0;
        // Walk backwards: remove assistant/tool messages, then the user message.
        while let Some(m) = session.messages.last() {
            if m.role == Role::User {
                session.messages.pop();
                removed += 1;
                break;
            }
            session.messages.pop();
            removed += 1;
        }
        removed
    }

    /// Force context compression on the next turn.
    pub async fn force_compress(&self) {
        let provider = self.provider.read().await.clone();
        let mut session = self.session.write().await;
        let params = crate::compression::CompressionParams::default();
        session.messages =
            crate::compression::compress_with_llm(&session.messages, &params, &provider).await;
    }

    /// Set the session title (persisted on next DB write).
    pub async fn set_session_title(&self, title: String) {
        let session = self.session.read().await;
        if let (Some(db), Some(sid)) = (&self.state_db, &session.session_id) {
            let _ = db.update_session_title(sid, &title);
        }
    }

    /// Restore a persisted session from the state DB into the live session state.
    pub async fn restore_session(&self, id: &str) -> Result<usize, AgentError> {
        let db = self
            .state_db
            .as_ref()
            .ok_or_else(|| AgentError::Config("No state database configured".into()))?;

        let record = db
            .get_session(id)?
            .ok_or_else(|| AgentError::Config(format!("Session not found: {id}")))?;
        let messages = db.get_messages(id)?;

        {
            let mut session = self.session.write().await;
            session.session_id = Some(record.id.clone());
            session.cached_system_prompt = None;
            session.user_turn_count = messages
                .iter()
                .filter(|m| matches!(m.role, edgecrab_types::Role::User))
                .count() as u32;
            session.api_call_count = 0;
            session.session_input_tokens = record.input_tokens.max(0) as u64;
            session.session_output_tokens = record.output_tokens.max(0) as u64;
            session.session_cache_read_tokens = record.cache_read_tokens.max(0) as u64;
            session.session_cache_write_tokens = record.cache_write_tokens.max(0) as u64;
            session.session_reasoning_tokens = record.reasoning_tokens.max(0) as u64;
            session.messages = messages;
        }

        if let Some(model) = record.model {
            let mut config = self.config.write().await;
            config.model = model;
        }
        self.budget.reset();

        Ok(self.session.read().await.messages.len())
    }

    /// List persisted sessions (delegates to SessionDb).
    pub fn list_sessions(
        &self,
        limit: usize,
    ) -> Result<Vec<edgecrab_state::SessionSummary>, AgentError> {
        match &self.state_db {
            Some(db) => db.list_sessions(limit),
            None => Ok(Vec::new()),
        }
    }

    /// Delete a persisted session by ID (delegates to SessionDb).
    pub fn delete_session(&self, id: &str) -> Result<(), AgentError> {
        match &self.state_db {
            Some(db) => db.delete_session(id),
            None => Err(AgentError::Config("No state database configured".into())),
        }
    }

    /// Rename a persisted session (set or change its title).
    pub fn rename_session(&self, id: &str, title: &str) -> Result<(), AgentError> {
        match &self.state_db {
            Some(db) => db.update_session_title(id, title),
            None => Err(AgentError::Config("No state database configured".into())),
        }
    }

    /// Prune old ended sessions. Returns the number of sessions deleted.
    pub fn prune_sessions(
        &self,
        older_than_days: u32,
        source: Option<&str>,
    ) -> Result<usize, AgentError> {
        match &self.state_db {
            Some(db) => db.prune_sessions(older_than_days, source),
            None => Err(AgentError::Config("No state database configured".into())),
        }
    }

    /// Check if a state database is configured.
    pub fn has_state_db(&self) -> bool {
        self.state_db.is_some()
    }

    /// Return a clone of the state DB handle, if configured.
    pub async fn state_db(&self) -> Option<Arc<SessionDb>> {
        self.state_db.clone()
    }

    /// Return a clone of the current provider handle.
    ///
    /// Used by the gateway for deterministic pre-processing steps such as
    /// eager image analysis before the conversation turn starts.
    pub async fn provider_handle(&self) -> Arc<dyn LLMProvider> {
        self.provider.read().await.clone()
    }

    /// Return a clone of the current auxiliary side-task routing config.
    pub async fn auxiliary_config(&self) -> crate::config::AuxiliaryConfig {
        self.config.read().await.auxiliary.clone()
    }

    /// List all registered tool names.
    pub async fn tool_names(&self) -> Vec<String> {
        match &self.tool_registry {
            Some(reg) => reg
                .tool_names()
                .into_iter()
                .map(|s| s.to_string())
                .collect(),
            None => Vec::new(),
        }
    }

    /// List toolsets with their tool counts.
    pub async fn toolset_summary(&self) -> Vec<(String, usize)> {
        match &self.tool_registry {
            Some(reg) => reg.toolset_summary(),
            None => Vec::new(),
        }
    }

    /// Set reasoning effort on the agent config.
    pub async fn set_reasoning_effort(&self, level: Option<String>) {
        let mut config = self.config.write().await;
        config.reasoning_effort = level;
    }

    /// Enable or disable live token streaming for future turns.
    pub async fn set_streaming(&self, enabled: bool) {
        let mut config = self.config.write().await;
        config.streaming = enabled;
        config.model_config.streaming = enabled;
    }

    /// Update auxiliary side-task routing for future turns.
    pub async fn set_auxiliary_config(&self, auxiliary: crate::config::AuxiliaryConfig) {
        let mut config = self.config.write().await;
        config.auxiliary = auxiliary;
    }
}

/// Read-only snapshot of current session state for display.
#[derive(Debug, Clone)]
pub struct SessionSnapshot {
    pub session_id: Option<String>,
    pub model: String,
    pub message_count: usize,
    pub user_turn_count: u32,
    pub api_call_count: u32,
    pub input_tokens: u64,
    pub output_tokens: u64,
    pub cache_read_tokens: u64,
    pub cache_write_tokens: u64,
    pub reasoning_tokens: u64,
    pub budget_remaining: u32,
    pub budget_max: u32,
}

/// Risk-graduated approval choices surfaced by `StreamEvent::Approval`.
///
/// - `Once`    — approve this specific invocation only.
/// - `Session` — approve all identical commands for the rest of the session.
/// - `Always`  — persist approval to disk so future sessions skip the dialog.
/// - `Deny`    — refuse; the agent should not execute the command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ApprovalChoice {
    Once,
    Session,
    Always,
    Deny,
}

/// Events sent from the streaming agent to the TUI.
///
/// WHY an enum: The channel carries multiple event types — partial
/// tokens, completion signal, and errors. A single `String` channel
/// can't distinguish done from error, forcing consumers to use
/// sentinel strings (fragile). An enum is explicit and exhaustive.
pub enum StreamEvent {
    /// A partial response token/chunk.
    Token(String),
    /// A reasoning / think-mode chunk.
    Reasoning(String),
    /// A tool execution has started.
    ToolExec {
        /// Tool name (e.g. "web_search")
        name: String,
        /// Raw JSON arguments string (for preview extraction in the TUI)
        args_json: String,
    },
    /// A tool execution has completed.
    ToolDone {
        /// Tool name (e.g. "web_search")
        name: String,
        /// Raw JSON arguments string (for preview extraction in the TUI)
        args_json: String,
        /// Elapsed milliseconds
        duration_ms: u64,
        /// Whether the result looks like an error
        is_error: bool,
    },
    /// The response is complete.
    Done,
    /// An error occurred — the response is incomplete.
    Error(String),
    /// The agent needs a clarifying answer from the user.
    /// The caller must send the answer to `response_tx` to unblock the agent.
    Clarify {
        question: String,
        /// Up to 4 predefined answer choices, or None for open-ended.
        choices: Option<Vec<String>>,
        response_tx: tokio::sync::oneshot::Sender<String>,
    },
    /// The agent is requesting approval before executing a potentially risky command.
    ///
    /// The caller presents a risk-graduated dialog (once / session / always / deny)
    /// and sends the user's `ApprovalChoice` to `response_tx` to unblock the agent.
    /// When `deny` is chosen the agent should abort the tool execution.
    Approval {
        /// Short human-readable description of the action to be approved.
        command: String,
        /// Full command string (may be >70 chars; "view" expands this in the TUI).
        full_command: String,
        /// Concrete policy reasons that caused the approval gate to trigger.
        reasons: Vec<String>,
        /// Channel to send the user's choice back to the agent.
        response_tx: tokio::sync::oneshot::Sender<ApprovalChoice>,
    },
    /// The agent is requesting a secret string from the user (e.g. an API key,
    /// environment variable value, or sudo password).
    ///
    /// The TUI should render a masked input overlay (`•••`) so the value never
    /// appears in the scrollback. It then sends the secret string to
    /// `response_tx` to unblock the agent. Sending an empty string aborts.
    SecretRequest {
        /// The name of the variable or credential being requested (e.g. "OPENAI_API_KEY").
        var_name: String,
        /// Human-readable prompt to show the user.
        prompt: String,
        /// Whether this is a sudo / privilege-escalation prompt (affects the UI colour).
        is_sudo: bool,
        /// Channel to send the secret value back to the agent (empty = abort).
        response_tx: tokio::sync::oneshot::Sender<String>,
    },
    /// A lifecycle hook event emitted from the conversation loop.
    ///
    /// Subscribers (gateway, CLI) receive these events and forward them to
    /// the `HookRegistry` so tool:pre/post and llm:pre/post hooks fire without
    /// creating a circular dependency from edgecrab-core into edgecrab-gateway.
    HookEvent {
        /// The event type (e.g. "tool:pre", "llm:post").
        event: String,
        /// JSON-serialized context payload.
        context_json: String,
    },
    /// Context pressure warning: token usage is approaching the compression threshold.
    ///
    /// Emitted when estimated tokens exceed 85 % of the compression threshold —
    /// before compression fires. The TUI / gateway surfaces this as a status
    /// indicator so the user knows the context is filling up. After a successful
    /// compression the status reverts to `Ok` (no event is emitted for that).
    ContextPressure {
        /// Estimated current token usage.
        estimated_tokens: usize,
        /// Compression threshold in tokens (context_window × threshold_fraction).
        threshold_tokens: usize,
    },
}

impl std::fmt::Debug for StreamEvent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Token(t) => write!(f, "Token({t:?})"),
            Self::Reasoning(t) => write!(f, "Reasoning({t:?})"),
            Self::ToolExec { name, .. } => write!(f, "ToolExec({name:?})"),
            Self::ToolDone {
                name,
                duration_ms,
                is_error,
                ..
            } => {
                write!(f, "ToolDone({name:?}, {duration_ms}ms, err={is_error})")
            }
            Self::Done => write!(f, "Done"),
            Self::Error(e) => write!(f, "Error({e:?})"),
            Self::Clarify {
                question, choices, ..
            } => {
                if choices.is_some() {
                    write!(f, "Clarify({question:?}, multiple-choice)")
                } else {
                    write!(f, "Clarify({question:?})")
                }
            }
            Self::Approval { command, .. } => write!(f, "Approval({command:?})"),
            Self::SecretRequest {
                var_name, is_sudo, ..
            } => write!(f, "SecretRequest({var_name:?}, sudo={is_sudo})"),
            Self::HookEvent { event, .. } => write!(f, "HookEvent({event:?})"),
            Self::ContextPressure {
                estimated_tokens,
                threshold_tokens,
            } => write!(
                f,
                "ContextPressure(est={estimated_tokens}, threshold={threshold_tokens})"
            ),
        }
    }
}

// ─── Helpers ─────────────────────────────────────────────────────────

/// Parse a platform name string into a `Platform` variant.
///
/// Used by `chat_with_origin` so the gateway can pass the string name
/// of the originating platform and get the correct platform hint into
/// the system prompt.
fn platform_from_str(s: &str) -> Option<Platform> {
    match s {
        "cli" => Some(Platform::Cli),
        "telegram" => Some(Platform::Telegram),
        "discord" => Some(Platform::Discord),
        "slack" => Some(Platform::Slack),
        "whatsapp" => Some(Platform::Whatsapp),
        "feishu" => Some(Platform::Feishu),
        "wecom" => Some(Platform::Wecom),
        "signal" => Some(Platform::Signal),
        "email" => Some(Platform::Email),
        "matrix" => Some(Platform::Matrix),
        "mattermost" => Some(Platform::Mattermost),
        "dingtalk" => Some(Platform::DingTalk),
        "sms" => Some(Platform::Sms),
        "webhook" => Some(Platform::Webhook),
        "api" | "api_server" => Some(Platform::Api),
        "homeassistant" => Some(Platform::HomeAssistant),
        "cron" => Some(Platform::Cron),
        _ => None,
    }
}

// ─── Builder ──────────────────────────────────────────────────────────

pub struct AgentBuilder {
    config: AgentConfig,
    provider: Option<Arc<dyn LLMProvider>>,
    state_db: Option<Arc<SessionDb>>,
    tool_registry: Option<Arc<ToolRegistry>>,
}

impl AgentBuilder {
    pub fn new(model: &str) -> Self {
        Self {
            config: AgentConfig {
                model: model.to_string(),
                ..Default::default()
            },
            provider: None,
            state_db: None,
            tool_registry: None,
        }
    }

    /// Construct from an existing AppConfig.
    pub fn from_config(config: &AppConfig) -> Self {
        // Resolve personality preset → persona instruction addon
        let personality_addon =
            crate::config::resolve_personality(config, &config.display.personality);

        Self {
            config: AgentConfig {
                model: config.model.default_model.clone(),
                enabled_toolsets: config.tools.enabled_toolsets.clone().unwrap_or_default(),
                disabled_toolsets: config.tools.disabled_toolsets.clone().unwrap_or_default(),
                max_iterations: config.model.max_iterations,
                streaming: config.model.streaming,
                save_trajectories: config.save_trajectories,
                skip_context_files: config.skip_context_files,
                skip_memory: config.skip_memory,
                temperature: config.model.temperature,
                model_config: config.model.clone(),
                skills_config: config.skills.clone(),
                delegation_enabled: config.delegation.enabled,
                delegation_model: config.delegation.model.clone(),
                delegation_provider: config.delegation.provider.clone(),
                delegation_max_subagents: config.delegation.max_subagents,
                delegation_max_iterations: config.delegation.max_iterations,
                personality_addon,
                browser: config.browser.clone(),
                checkpoints_enabled: config.checkpoints.enabled,
                checkpoints_max_snapshots: config.checkpoints.max_snapshots,
                terminal_backend: config.terminal.backend.clone(),
                terminal_docker: config.terminal.docker.clone(),
                terminal_ssh: config.terminal.ssh.clone(),
                terminal_modal: config.terminal.modal.clone(),
                terminal_daytona: config.terminal.daytona.clone(),
                terminal_singularity: config.terminal.singularity.clone(),
                auxiliary: config.auxiliary.clone(),
                terminal_env_passthrough: config.terminal.env_passthrough.clone(),
                file_allowed_roots: config.tools.file.allowed_roots.clone(),
                path_restrictions: config.security.path_restrictions.clone(),
                ..Default::default()
            },
            provider: None,
            state_db: None,
            tool_registry: None,
        }
    }

    pub fn provider(mut self, p: Arc<dyn LLMProvider>) -> Self {
        self.provider = Some(p);
        self
    }

    pub fn state_db(mut self, db: Arc<SessionDb>) -> Self {
        self.state_db = Some(db);
        self
    }

    pub fn tools(mut self, registry: Arc<ToolRegistry>) -> Self {
        self.tool_registry = Some(registry);
        self
    }

    pub fn max_iterations(mut self, n: u32) -> Self {
        self.config.max_iterations = n;
        self
    }

    pub fn streaming(mut self, enabled: bool) -> Self {
        self.config.streaming = enabled;
        self
    }

    pub fn platform(mut self, p: Platform) -> Self {
        self.config.platform = p;
        self
    }

    pub fn session_id(mut self, id: String) -> Self {
        self.config.session_id = Some(id);
        self
    }

    /// Set the origin chat context — (platform_name, chat_id) — for gateway sessions.
    ///
    /// This is forwarded into every `ToolContext` so that
    /// `manage_cron_jobs(action='create', deliver='origin')` knows where to
    /// deliver job output without the LLM needing to know the raw chat ID.
    pub fn origin_chat(mut self, platform: String, chat_id: String) -> Self {
        self.config.origin_chat = Some((platform, chat_id));
        self
    }

    pub fn temperature(mut self, t: f32) -> Self {
        self.config.temperature = Some(t);
        self
    }

    pub fn quiet_mode(mut self, enabled: bool) -> Self {
        self.config.quiet_mode = enabled;
        self
    }

    pub fn build(self) -> Result<Agent, AgentError> {
        let provider = self
            .provider
            .ok_or_else(|| AgentError::Config("provider is required".into()))?;
        Ok(Agent::build_runtime_clone(
            self.config,
            provider,
            self.state_db,
            self.tool_registry,
        ))
    }
}

// ─── Agent Drop ───────────────────────────────────────────────────────

impl Drop for Agent {
    /// Cancel the GC task when the Agent is dropped so the background
    /// tokio task doesn't outlive the process table it references.
    fn drop(&mut self) {
        self.gc_cancel.cancel();
    }
}

// ─── Tests ────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use edgecrab_tools::registry::GatewaySender;
    use edgequake_llm::traits::{
        ChatMessage, CompletionOptions, StreamChunk, ToolChoice, ToolDefinition,
    };
    use futures::StreamExt;

    struct ReasoningStreamProvider;
    struct MockGatewaySender;

    #[test]
    fn platform_from_str_accepts_gateway_api_server_alias() {
        assert_eq!(platform_from_str("api"), Some(Platform::Api));
        assert_eq!(platform_from_str("api_server"), Some(Platform::Api));
    }

    #[async_trait]
    impl LLMProvider for ReasoningStreamProvider {
        fn name(&self) -> &str {
            "reasoning-stream"
        }

        fn model(&self) -> &str {
            "reasoning-stream/mock"
        }

        fn max_context_length(&self) -> usize {
            128_000
        }

        async fn complete(
            &self,
            _prompt: &str,
        ) -> edgequake_llm::Result<edgequake_llm::LLMResponse> {
            Ok(edgequake_llm::LLMResponse::new(
                "fallback complete",
                self.model(),
            ))
        }

        async fn complete_with_options(
            &self,
            prompt: &str,
            _options: &CompletionOptions,
        ) -> edgequake_llm::Result<edgequake_llm::LLMResponse> {
            self.complete(prompt).await
        }

        async fn chat(
            &self,
            messages: &[ChatMessage],
            options: Option<&CompletionOptions>,
        ) -> edgequake_llm::Result<edgequake_llm::LLMResponse> {
            self.chat_with_tools(messages, &[], None, options).await
        }

        async fn chat_with_tools(
            &self,
            _messages: &[ChatMessage],
            _tools: &[ToolDefinition],
            _tool_choice: Option<ToolChoice>,
            _options: Option<&CompletionOptions>,
        ) -> edgequake_llm::Result<edgequake_llm::LLMResponse> {
            let mut response = edgequake_llm::LLMResponse::new("nonstreamed answer", self.model());
            response.thinking_content = Some("hidden reasoning".to_string());
            Ok(response)
        }

        async fn stream(
            &self,
            _prompt: &str,
        ) -> edgequake_llm::Result<futures::stream::BoxStream<'static, edgequake_llm::Result<String>>>
        {
            Ok(futures::stream::iter(vec![Ok("plain stream".to_string())]).boxed())
        }

        async fn chat_with_tools_stream(
            &self,
            _messages: &[ChatMessage],
            _tools: &[ToolDefinition],
            _tool_choice: Option<ToolChoice>,
            _options: Option<&CompletionOptions>,
        ) -> edgequake_llm::Result<
            futures::stream::BoxStream<'static, edgequake_llm::Result<StreamChunk>>,
        > {
            let chunks = vec![
                Ok(StreamChunk::ThinkingContent {
                    text: "live reasoning".to_string(),
                    tokens_used: Some(3),
                    budget_total: None,
                }),
                Ok(StreamChunk::Content("streamed answer".to_string())),
                Ok(StreamChunk::Finished {
                    reason: "stop".to_string(),
                    ttft_ms: None,
                    usage: None,
                }),
            ];
            Ok(futures::stream::iter(chunks).boxed())
        }

        fn supports_streaming(&self) -> bool {
            true
        }

        fn supports_tool_streaming(&self) -> bool {
            true
        }

        fn supports_function_calling(&self) -> bool {
            true
        }
    }

    #[async_trait]
    impl GatewaySender for MockGatewaySender {
        async fn send_message(
            &self,
            _platform: &str,
            _recipient: &str,
            _message: &str,
        ) -> Result<(), String> {
            Ok(())
        }

        async fn list_targets(&self) -> Result<Vec<String>, String> {
            Ok(vec!["telegram".into()])
        }
    }

    #[test]
    fn iteration_budget_counts_down() {
        let budget = IterationBudget::new(3);
        assert!(budget.try_consume());
        assert!(budget.try_consume());
        assert!(budget.try_consume());
        assert!(!budget.try_consume());
        assert_eq!(budget.used(), 3);
    }

    #[test]
    fn iteration_budget_reset() {
        let budget = IterationBudget::new(2);
        budget.try_consume();
        budget.try_consume();
        assert!(!budget.try_consume());
        budget.reset();
        assert!(budget.try_consume());
        assert_eq!(budget.remaining(), 1);
    }

    #[test]
    fn builder_requires_provider() {
        let result = AgentBuilder::new("test/model").build();
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn builder_with_mock_provider() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let agent = AgentBuilder::new("mock")
            .provider(provider)
            .max_iterations(10)
            .build()
            .expect("build agent");

        let cfg = agent.config.read().await;
        assert_eq!(cfg.model, "mock");
        assert_eq!(cfg.max_iterations, 10);
        assert_eq!(agent.budget.remaining(), 10);
    }

    #[tokio::test]
    async fn chat_with_mock_provider() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let agent = AgentBuilder::new("mock")
            .provider(provider)
            .build()
            .expect("build agent");

        let result = agent.chat("hello").await;
        assert!(result.is_ok());
        // MockProvider returns a canned response
        let response = result.expect("response");
        assert!(!response.is_empty());
    }

    #[test]
    fn from_config_wires_agent_flags() {
        let config = AppConfig {
            save_trajectories: true,
            skip_context_files: true,
            skip_memory: true,
            ..Default::default()
        };

        let builder = AgentBuilder::from_config(&config);

        assert!(builder.config.save_trajectories);
        assert!(builder.config.skip_context_files);
        assert!(builder.config.skip_memory);
    }

    #[tokio::test]
    async fn new_session_resets_state() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let agent = AgentBuilder::new("mock")
            .provider(provider)
            .max_iterations(5)
            .build()
            .expect("build agent");

        // Use some budget
        agent.budget.try_consume();
        agent.budget.try_consume();
        assert_eq!(agent.budget.remaining(), 3);

        // Chat to add messages
        let _ = agent.chat("hi").await;

        // Reset
        agent.new_session().await;
        assert_eq!(agent.budget.remaining(), 5);
        let session = agent.session.read().await;
        assert!(session.messages.is_empty());
    }

    #[tokio::test]
    async fn interrupt_triggers_cancellation() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let agent = AgentBuilder::new("mock")
            .provider(provider)
            .build()
            .expect("build agent");

        assert!(!agent.is_cancelled());
        agent.interrupt();
        assert!(agent.is_cancelled());
    }

    /// After an interrupt, execute_loop must reset the cancel token so the
    /// agent can still process subsequent conversation turns.  Without this
    /// reset, Ctrl+C would permanently break the agent for the rest of the
    /// session.
    #[tokio::test]
    async fn cancel_resets_between_turns() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let agent = AgentBuilder::new("mock")
            .provider(provider)
            .build()
            .expect("build agent");

        // Interrupt and confirm the token is now cancelled
        agent.interrupt();
        assert!(agent.is_cancelled());

        // A new chat call should succeed — execute_loop resets the token
        let result = agent.chat("hello after cancel").await;
        assert!(result.is_ok(), "expected success after cancel: {result:?}");
        // Token must not still be cancelled after a clean (non-interrupted) turn
        assert!(!agent.is_cancelled());
    }

    #[tokio::test]
    async fn conversation_result_structure() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let agent = AgentBuilder::new("mock")
            .provider(provider)
            .session_id("test-session".into())
            .build()
            .expect("build agent");

        let result = agent
            .run_conversation("hello", Some("You are helpful."), None)
            .await
            .expect("conversation");

        assert_eq!(result.session_id, "test-session");
        assert_eq!(result.api_calls, 1);
        assert!(!result.interrupted);
        assert_eq!(result.model, "mock");
        // Messages: user + assistant
        assert_eq!(result.messages.len(), 2);
    }

    #[tokio::test]
    async fn session_state_gets_session_id_after_chat() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let agent = AgentBuilder::new("mock")
            .provider(provider)
            .build()
            .expect("build agent");

        // Before chat, session_id is None
        {
            let session = agent.session.read().await;
            assert!(session.session_id.is_none());
        }

        // After chat, session_id is populated (auto-generated UUID)
        let _ = agent.chat("hello").await;
        {
            let session = agent.session.read().await;
            assert!(session.session_id.is_some());
        }
    }

    #[tokio::test]
    async fn fork_isolated_creates_fresh_session_state() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let parent = AgentBuilder::new("mock")
            .provider(provider)
            .max_iterations(7)
            .build()
            .expect("build agent");

        let _ = parent.chat("parent turn").await.expect("parent chat");
        let parent_before = parent.session_snapshot().await;

        let child = parent
            .fork_isolated(IsolatedAgentOptions {
                session_id: Some("bg-test".into()),
                quiet_mode: Some(true),
                ..Default::default()
            })
            .await
            .expect("fork isolated");

        let child_before = child.session_snapshot().await;
        let child_cfg = child.config.read().await;
        assert_eq!(child_before.message_count, 0);
        assert_eq!(child_before.api_call_count, 0);
        assert_eq!(child_before.model, parent_before.model);
        assert_eq!(child_cfg.session_id.as_deref(), Some("bg-test"));
        assert_eq!(child.budget.remaining(), 7);
        drop(child_cfg);

        let _ = child.chat("background turn").await.expect("child chat");

        let parent_after = parent.session_snapshot().await;
        let child_after = child.session_snapshot().await;
        assert_eq!(parent_after.message_count, parent_before.message_count);
        assert!(child_after.message_count > 0);
        assert_eq!(child_after.session_id.as_deref(), Some("bg-test"));
        assert_ne!(parent_after.session_id, child_after.session_id);
    }

    #[tokio::test]
    async fn fork_isolated_preserves_gateway_sender() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let parent = AgentBuilder::new("mock")
            .provider(provider)
            .build()
            .expect("build agent");
        parent.set_gateway_sender(Arc::new(MockGatewaySender)).await;

        let child = parent
            .fork_isolated(IsolatedAgentOptions::default())
            .await
            .expect("fork isolated");

        assert!(child.gateway_sender.read().await.is_some());
    }

    #[tokio::test]
    async fn model_config_propagates_to_agent() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let agent = AgentBuilder::new("mock")
            .provider(provider)
            .build()
            .expect("build agent");

        let cfg = agent.config.read().await;
        assert!(!cfg.model_config.smart_routing.enabled);
        assert!(cfg.model_config.smart_routing.cheap_model.is_empty());
    }

    #[tokio::test]
    async fn chat_streaming_emits_reasoning_when_enabled() {
        let provider: Arc<dyn LLMProvider> = Arc::new(ReasoningStreamProvider);
        let agent = AgentBuilder::new("reasoning-stream/mock")
            .provider(provider)
            .streaming(true)
            .build()
            .expect("build agent");

        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        agent
            .chat_streaming("hello", tx)
            .await
            .expect("streaming chat");

        let mut saw_reasoning = false;
        let mut saw_token = false;
        let mut saw_done = false;

        while let Some(event) = rx.recv().await {
            match event {
                StreamEvent::Reasoning(text) => saw_reasoning |= !text.is_empty(),
                StreamEvent::Token(text) => saw_token |= !text.is_empty(),
                StreamEvent::Done => {
                    saw_done = true;
                    break;
                }
                _ => {}
            }
        }

        assert!(
            saw_reasoning,
            "expected a live reasoning event when streaming is enabled"
        );
        assert!(saw_token, "expected streamed answer tokens");
        assert!(saw_done, "expected the stream to terminate cleanly");
    }

    #[tokio::test]
    async fn chat_streaming_sends_single_final_answer_when_streaming_disabled() {
        let provider: Arc<dyn LLMProvider> = Arc::new(ReasoningStreamProvider);
        let agent = AgentBuilder::new("reasoning-stream/mock")
            .provider(provider)
            .streaming(false)
            .build()
            .expect("build agent");

        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        agent
            .chat_streaming("hello", tx)
            .await
            .expect("streaming chat");

        let mut saw_reasoning = false;
        let mut token_events = 0usize;
        let mut collected_tokens = String::new();

        while let Some(event) = rx.recv().await {
            match event {
                StreamEvent::Reasoning(text) => saw_reasoning |= !text.is_empty(),
                StreamEvent::Token(text) => {
                    token_events += 1;
                    collected_tokens.push_str(&text);
                }
                StreamEvent::Done => break,
                _ => {}
            }
        }

        assert!(
            saw_reasoning,
            "final reasoning content should still be available for think mode"
        );
        assert_eq!(
            token_events, 1,
            "streaming-off mode should emit one complete answer instead of pseudo-streaming chunks"
        );
        assert_eq!(collected_tokens, "nonstreamed answer");
    }

    #[tokio::test]
    async fn session_personality_overlay_replaces_previous_overlay() {
        let provider: Arc<dyn LLMProvider> = Arc::new(edgequake_llm::MockProvider::new());
        let agent = AgentBuilder::new("mock")
            .provider(provider)
            .build()
            .expect("build agent");

        {
            let mut session = agent.session.write().await;
            session.cached_system_prompt = Some("Base prompt".to_string());
        }

        agent
            .set_personality_addon(Some("First overlay".to_string()))
            .await;
        assert!(agent.system_prompt().await.is_none());

        {
            let mut session = agent.session.write().await;
            session.cached_system_prompt = Some("Base prompt".to_string());
        }

        agent
            .set_personality_addon(Some("Second overlay".to_string()))
            .await;
        assert!(agent.system_prompt().await.is_none());

        agent.set_personality_addon(None).await;
        assert!(agent.system_prompt().await.is_none());
    }
}