rsclaw 2026.4.22

AI Agent Engine Compatible with OpenClaw
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
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
//! rsclaw JSON5 config schema — full field coverage.
//! Unknown fields cause deserialization to fail (deny_unknown_fields).

use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use serde_json::Value;

// ---------------------------------------------------------------------------
// Top-level
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct Config {
    // --- Core ---
    #[serde(rename = "$schema")]
    pub schema: Option<String>,
    pub meta: Option<MetaConfig>,
    pub gateway: Option<GatewayConfig>,
    pub update: Option<UpdateConfig>,
    pub env: Option<EnvConfig>,
    pub agents: Option<AgentsConfig>,
    pub models: Option<ModelsConfig>,
    pub auth: Option<AuthConfig>,
    pub channels: Option<ChannelsConfig>,
    pub session: Option<SessionConfig>,
    pub bindings: Option<Vec<BindingConfig>>,
    pub cron: Option<CronConfig>,
    pub tools: Option<ToolsConfig>,
    pub sandbox: Option<SandboxConfig>,
    pub logging: Option<LoggingConfig>,
    pub skills: Option<SkillsConfig>,
    pub plugins: Option<PluginsConfig>,
    pub hooks: Option<HooksConfig>,
    pub secrets: Option<SecretsConfig>,
    pub memory_search: Option<MemorySearchConfig>,
    pub memory: Option<MemoryTopConfig>,
    pub mcp: Option<McpConfig>,

    // --- OpenClaw-compatible sections ---
    pub wizard: Option<Value>,
    pub messages: Option<MessagesConfig>,
    pub commands: Option<CommandsConfig>,
    pub diagnostics: Option<Value>,
    pub cli: Option<CliConfig>,
    pub browser: Option<BrowserConfig>,
    pub ui: Option<UiConfig>,
    pub acp: Option<Value>,
    pub node_host: Option<Value>,
    pub broadcast: Option<Value>,
    pub audio: Option<Value>,
    pub media: Option<Value>,
    pub approvals: Option<ApprovalsConfig>,
    pub discovery: Option<Value>,
    pub canvas_host: Option<CanvasHostConfig>,
    pub talk: Option<TalkConfig>,
    pub web: Option<WebConfig>,
}

// ---------------------------------------------------------------------------
// meta
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MetaConfig {
    pub version: Option<String>,
    pub name: Option<String>,
    /// OpenClaw uses lastTouchedVersion/lastTouchedAt
    pub last_touched_version: Option<String>,
    pub last_touched_at: Option<String>,
    pub timestamp: Option<u64>,
}

// ---------------------------------------------------------------------------
// gateway
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct GatewayConfig {
    pub port: Option<u16>,
    pub mode: Option<GatewayMode>,
    pub bind: Option<BindMode>,
    /// Custom bind address (IP string like "192.168.0.169"). Used when bind is
    /// an IP address string instead of a named mode.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bind_address: Option<String>,
    pub auth: Option<GatewayAuth>,
    pub control_ui: Option<ControlUiConfig>,
    pub reload: Option<ReloadMode>,
    pub push: Option<PushConfig>,
    pub channel_health_check_minutes: Option<u32>,
    pub channel_stale_event_threshold_minutes: Option<u32>,
    pub channel_max_restarts_per_hour: Option<u32>,
    pub remote: Option<Value>,
    pub tailscale: Option<Value>,
    pub hot_reload: Option<Value>,
    /// Default response language (e.g. "Chinese", "English", "Japanese").
    pub language: Option<String>,
    /// Seconds before sending "Processing..." indicator. 0 = disabled. Default: 10.
    pub processing_timeout: Option<u64>,
    /// Global default User-Agent for all LLM provider HTTP requests.
    /// Provider-level user_agent overrides this. Default: "Mozilla/5.0 (compatible; rsclaw/1.0)".
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user_agent: Option<String>,
    /// Global HTTP/SOCKS5 proxy URL (e.g. "http://127.0.0.1:7890", "socks5://proxy:1080").
    /// Env var RSCLAW_PROXY overrides this.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub proxy: Option<String>,
    /// Proxy allow list: only matching domains use the proxy.
    /// Supports wildcards: "*.openai.com,api.anthropic.com,github.com"
    /// "*" means all domains use proxy. Empty/unset = all (default).
    /// Env var RSCLAW_PROXY_ALLOW overrides this.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub proxy_allow: Option<String>,
    /// Proxy deny list: matching domains bypass the proxy (added to NO_PROXY).
    /// "localhost,127.0.0.1,192.168.*,10.*"
    /// Env var RSCLAW_PROXY_DENY overrides this.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub proxy_deny: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum GatewayMode {
    Local,
    Cloud,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum BindMode {
    Auto,
    Lan,
    Loopback,
    All,
    Custom,
    Tailnet,
}

impl BindMode {
    /// Parse a bind string that might be an enum variant or an IP address.
    pub fn from_config_str(s: &str) -> (Self, Option<String>) {
        match s.to_lowercase().as_str() {
            "auto" => (Self::Auto, None),
            "lan" => (Self::Lan, None),
            "loopback" => (Self::Loopback, None),
            "all" => (Self::All, None),
            "custom" => (Self::Custom, None),
            "tailnet" => (Self::Tailnet, None),
            // Treat as IP address
            _ => (Self::Custom, Some(s.to_owned())),
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GatewayAuth {
    pub mode: Option<String>,
    pub token: Option<SecretOrString>,
    pub password: Option<SecretOrString>,
    pub allow_tailscale: Option<bool>,
    pub allow_local: Option<bool>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ControlUiConfig {
    pub enabled: Option<bool>,
    pub path: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum ReloadMode {
    Hot,
    Hybrid,
    Restart,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PushConfig {
    pub apns: Option<ApnsConfig>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApnsConfig {
    pub relay_url: Option<String>,
    pub token: Option<SecretOrString>,
}

// ---------------------------------------------------------------------------
// update
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateConfig {
    pub channel: Option<String>,
    pub auto: Option<bool>,
    pub check: Option<bool>,
    pub notify: Option<bool>,
}

// ---------------------------------------------------------------------------
// env
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct EnvConfig(pub HashMap<String, String>);

// ---------------------------------------------------------------------------
// agents
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExternalAgentConfig {
    /// Logical agent ID (used as `agent_<id>` tool name).
    pub id: String,
    /// Base URL of the remote rsclaw/OpenClaw gateway, e.g. "http://host:18888".
    pub url: String,
    /// Optional bearer token for the remote gateway.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auth_token: Option<String>,
    /// Remote agent ID to target. If omitted, uses the remote gateway's default agent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub remote_agent_id: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct AgentsConfig {
    pub defaults: Option<AgentDefaults>,
    pub list: Option<Vec<AgentEntry>>,
    pub external: Option<Vec<ExternalAgentConfig>>,
}

#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct AgentDefaults {
    pub workspace: Option<String>,
    pub model: Option<ModelConfig>,
    /// Cheap/fast model used for internal low-stakes sub-tasks: query
    /// planning, intent classification, summarization hints, etc. Falls back
    /// to `model` when unset. Keep it pointed at something ~50x cheaper than
    /// the main model (gpt-4o-mini / qwen-turbo / doubao-lite / local 1.5B).
    pub flash_model: Option<ModelConfig>,
    pub models: Option<HashMap<String, ModelAlias>>,
    pub max_concurrent: Option<u32>,
    pub context_pruning: Option<ContextPruningConfig>,
    pub compaction: Option<CompactionConfig>,
    pub heartbeat: Option<HeartbeatConfig>,
    pub sandbox: Option<AgentSandboxConfig>,
    pub image_max_dimension_px: Option<u32>,
    pub group_chat: Option<GroupChatConfig>,
    pub skip_bootstrap: Option<bool>,
    pub block_streaming_default: Option<bool>,
    pub timeout_seconds: Option<u32>,
    pub prompt_mode: Option<PromptMode>,
    pub memory: Option<MemoryConfig>,
    pub subagents: Option<Value>,
    pub bootstrap: Option<Value>,
    pub image: Option<Value>,
    pub pdf: Option<Value>,
    pub image_gen: Option<Value>,
    pub repo_root: Option<String>,
    pub context_tokens: Option<u32>,
    /// KV cache mode: 0 = off, 1 = full/append-only (default), 2 = delta/incremental.
    pub kv_cache_mode: Option<u8>,
    /// Maximum token budget for /ctx (btw) side queries. Default: 10000.
    pub btw_tokens: Option<u32>,
    pub timezone: Option<String>,
    pub timestamp: Option<Value>,
    pub thinking: Option<ThinkingConfig>,
    pub strip_think_tags: Option<bool>,
    pub frequency_penalty: Option<f32>,
    pub streaming: Option<StreamingMode>,
    pub timeout: Option<Value>,
    pub tools: Option<Value>,
    pub subagent: Option<Value>,
    pub cli: Option<Value>,
    pub media: Option<Value>,
    pub embedded: Option<Value>,
    pub archive: Option<Value>,
    /// Max tool-call iterations per turn. Simple tasks default to 10, complex (browser) to 100.
    pub max_iterations: Option<u32>,
    /// Send intermediate text to user during multi-step tool calls. Default: true.
    pub intermediate_output: Option<bool>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentEntry {
    pub id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workspace: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<ModelConfig>,
    /// Per-agent flash model override. Falls back to defaults.flash_model,
    /// then to this agent's `model`, then to defaults.model.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub flash_model: Option<ModelConfig>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lane: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lane_concurrency: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub group_chat: Option<GroupChatConfig>,
    /// rsclaw extension: which channels this agent handles (None = all)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub channels: Option<Vec<String>>,
    /// Custom slash commands for this agent (in addition to built-in ones)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub commands: Option<Vec<AgentCommand>>,
    /// Allowed pre-parsed commands: "*" = all (default for main agent),
    /// pipe-separated list = specific (e.g. "/help|/search|/version"),
    /// empty/null = none (default for non-main agents).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allowed_commands: Option<String>,
    /// rsclaw extension: use OpenCode ACP client instead of LLM
    /// When set, this agent spawns opencode acp subprocess and routes all prompts through it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub opencode: Option<OpenCodeConfig>,
    /// rsclaw extension: use Claude Code ACP client instead of LLM
    /// When set, this agent spawns claude-agent-acp subprocess and routes all prompts through it.
    /// Uses the official Claude Agent SDK via ACP protocol.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub claudecode: Option<ClaudeCodeConfig>,
    /// OpenClaw-specific
    #[serde(skip_serializing_if = "Option::is_none")]
    pub agent_dir: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system: Option<String>,
}

/// OpenCode ACP configuration for an agent.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OpenCodeConfig {
    /// Path to opencode binary (default: "opencode")
    pub command: Option<String>,
    /// Arguments passed to opencode acp (default: ["acp"])
    pub args: Option<Vec<String>>,
    /// Workspace directory for opencode (default: ".")
    pub cwd: Option<String>,
    /// Default model ID (e.g., "opencode/big-pickle", "alibaba/qwen3.5-plus")
    pub model: Option<String>,
}

/// Claude Code ACP configuration for an agent.
/// Uses claude-agent-acp (https://github.com/agentclientprotocol/claude-agent-acp)
/// which wraps the Claude Agent SDK with ACP protocol.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClaudeCodeConfig {
    /// Path to claude-agent-acp binary (default: "claude-agent-acp")
    pub command: Option<String>,
    /// Arguments passed to claude-agent-acp (default: [])
    pub args: Option<Vec<String>>,
    /// Workspace directory for claude code (default: agent's workspace)
    pub cwd: Option<String>,
    /// Claude model ID (e.g., "claude-sonnet-4-6", "claude-opus-4-6")
    pub model: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentCommand {
    /// Command name without slash (e.g. "deploy")
    pub name: String,
    /// Description shown in /help
    pub description: String,
    /// What to execute: tool name or shell command
    pub action: String,
    /// Optional: static arguments
    pub args: Option<Value>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub primary: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fallbacks: Option<Vec<String>>,
    /// Text-to-image model, e.g. "doubao/doubao-seedream-5-0-260128".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image_fallbacks: Option<Vec<String>>,
    /// Text-to-video model, e.g. "doubao/seedance-1-0-lite-t2v-250428".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub video: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thinking: Option<ThinkingConfig>,
    /// Whether to send tool definitions to the model. Default: true.
    /// Set to false for reasoning models (deepseek-r1, qwen-r1) that don't support tools.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools_enabled: Option<bool>,
    /// Tool set level: "minimal" (7 core), "standard" (12, default), "full" (all 32+).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub toolset: Option<String>,
    /// Extra tool names to include on top of the toolset level.
    /// Also used as a whitelist when toolset is not set.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<String>>,
    /// Context window size in tokens. Used to calculate history budget.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context_tokens: Option<u32>,
    /// Maximum tokens for LLM response. Default: 2048.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<u32>,
    /// Cheap/fast model for internal sub-tasks (query planning, intent
    /// classification, summarization). Falls back to `primary` when unset.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub flash: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum ThinkingLevel {
    Off,
    Minimal,
    Low,
    Medium,
    High,
    Xhigh,
    Adaptive,
}

impl ThinkingLevel {
    /// Map a thinking level to a recommended budget_tokens value.
    pub fn budget_tokens(&self) -> u32 {
        match self {
            ThinkingLevel::Off => 0,
            ThinkingLevel::Minimal => 1024,
            ThinkingLevel::Low => 4096,
            ThinkingLevel::Medium => 10240,
            ThinkingLevel::High => 32768,
            ThinkingLevel::Xhigh => 65536,
            ThinkingLevel::Adaptive => 0, // let the model decide
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThinkingConfig {
    pub enabled: Option<bool>,
    pub level: Option<ThinkingLevel>,
    pub budget_tokens: Option<u32>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelAlias {
    pub model: Option<String>,
    pub alias: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GroupChatConfig {
    pub enabled: Option<bool>,
    pub mention: Option<bool>,
    pub prefix: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum PromptMode {
    Full,
    Minimal,
}

// ---------------------------------------------------------------------------
// contextPruning
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ContextPruningConfig {
    pub mode: Option<PruningMode>,
    pub ttl: Option<String>,
    pub keep_last_assistants: Option<u32>,
    pub min_prunable_tool_chars: Option<u32>,
    pub soft_trim: Option<SoftTrimConfig>,
    pub hard_clear: Option<HardClearConfig>,
    pub tools: Option<PruningToolPolicy>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum PruningMode {
    Off,
    #[serde(rename = "cache-ttl")]
    CacheTtl,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SoftTrimConfig {
    pub enabled: Option<bool>,
    pub head_chars: Option<u32>,
    pub tail_chars: Option<u32>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HardClearConfig {
    pub enabled: Option<bool>,
    pub threshold: Option<u32>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PruningToolPolicy {
    pub deny: Option<Vec<String>>,
}

// ---------------------------------------------------------------------------
// compaction
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CompactionConfig {
    pub mode: Option<CompactionMode>,
    pub reserve_tokens_floor: Option<u32>,
    pub identifier_policy: Option<String>,
    pub memory_flush: Option<MemoryFlushConfig>,
    pub model: Option<String>,
    /// Number of recent user-assistant pairs to keep intact during layered
    /// compaction (default 5). Only older messages are summarised.
    pub keep_recent_pairs: Option<u32>,
    /// When true, extract key facts from compacted history and store them
    /// in long-term memory (default true).
    pub extract_facts: Option<bool>,
    /// Maximum token budget for the transcript text fed to the compact LLM.
    /// Higher values preserve more tool call/result detail but require a
    /// compact model with sufficient context window. Default: 16000 tokens.
    pub max_transcript_tokens: Option<usize>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum CompactionMode {
    Default,
    Safeguard,
    /// Keep last N turns verbatim, summarise only the older portion.
    Layered,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MemoryFlushConfig {
    pub enabled: Option<bool>,
    pub system_prompt: Option<String>,
    pub prompt: Option<String>,
}

// ---------------------------------------------------------------------------
// heartbeat
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HeartbeatConfig {
    pub enabled: Option<bool>,
}

// ---------------------------------------------------------------------------
// sandbox (agent level)
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentSandboxConfig {
    pub enabled: Option<bool>,
    pub scope: Option<SandboxScope>,
    pub browser_force: Option<bool>,
}

// ---------------------------------------------------------------------------
// models
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelsConfig {
    pub mode: Option<ModelsMode>,
    pub providers: HashMap<String, ProviderConfig>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum ModelsMode {
    Merge,
    Replace,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProviderConfig {
    pub base_url: Option<String>,
    pub api_key: Option<SecretOrString>,
    pub api: Option<ApiFormat>,
    pub models: Option<Vec<ModelDef>>,
    pub enabled: Option<bool>,
    /// Custom User-Agent for HTTP requests to this provider.
    /// Falls back to gateway.user_agent if not set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user_agent: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum ApiFormat {
    #[serde(rename = "openai-responses")]
    OpenAiResponses,
    #[serde(rename = "openai-completions", alias = "openai")]
    OpenAiCompletions,
    Anthropic,
    #[serde(rename = "anthropic-messages")]
    AnthropicMessages,
    Gemini,
    Ollama,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelDef {
    pub id: String,
    pub name: Option<String>,
    pub reasoning: Option<bool>,
    pub input: Option<Vec<InputType>>,
    pub cost: Option<CostConfig>,
    pub context_window: Option<u64>,
    pub max_tokens: Option<u64>,
    pub enabled: Option<bool>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum InputType {
    Text,
    Image,
    Audio,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CostConfig {
    pub input: Option<f64>,
    pub output: Option<f64>,
    pub unit: Option<u64>,
}

// ---------------------------------------------------------------------------
// auth
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthConfig {
    pub profiles: Option<HashMap<String, AuthProfile>>,
    pub order: Option<HashMap<String, Vec<String>>>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(tag = "mode", rename_all = "camelCase")]
pub enum AuthProfile {
    #[serde(rename = "oauth")]
    OAuth { email: Option<String> },
    #[serde(rename = "api_key")]
    ApiKey {
        #[serde(rename = "apiKey")]
        api_key: Option<SecretOrString>,
        provider: Option<String>,
    },
    #[serde(rename = "token")]
    Token {
        token: Option<SecretOrString>,
        provider: Option<String>,
    },
}

// ---------------------------------------------------------------------------
// channels
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ChannelsConfig {
    pub telegram: Option<TelegramConfig>,
    pub discord: Option<DiscordConfig>,
    pub slack: Option<SlackConfig>,
    pub whatsapp: Option<WhatsAppConfig>,
    pub signal: Option<SignalConfig>,
    pub imessage: Option<IMessageConfig>,
    pub mattermost: Option<MattermostConfig>,
    pub msteams: Option<MSTeamsConfig>,
    pub googlechat: Option<GoogleChatConfig>,
    pub feishu: Option<FeishuConfig>,
    pub dingtalk: Option<DingTalkConfig>,
    pub wecom: Option<WeComConfig>,
    /// Personal WeChat via ilink (openclaw-weixin compatible)
    pub wechat: Option<WeChatPersonalConfig>,
    /// QQ Official Bot API
    pub qq: Option<QQBotConfig>,
    /// LINE Messaging API
    pub line: Option<LineConfig>,
    /// Zalo Official Account API
    pub zalo: Option<ZaloConfig>,
    /// Matrix (Element) via Client-Server API long-poll sync
    pub matrix: Option<MatrixConfig>,
    /// Custom channels defined by the user (webhook or websocket).
    pub custom: Option<Vec<CustomChannelConfig>>,
}

// --- Custom user-defined channels ---

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomChannelConfig {
    /// Channel name (used in session keys, routing).
    pub name: String,
    /// "webhook" or "websocket".
    #[serde(rename = "type")]
    pub channel_type: String,
    #[serde(flatten)]
    pub base: ChannelBase,

    // -- WebSocket mode --
    /// WebSocket URL to connect to.
    pub ws_url: Option<String>,
    /// Extra headers for WS connection (e.g. auth).
    pub ws_headers: Option<HashMap<String, String>>,
    /// Auth frame to send after WS connect (JSON string with ${VAR} expansion).
    pub auth_frame: Option<String>,
    /// JSON path in auth response to check for success.
    pub auth_success_path: Option<String>,
    /// Expected value at auth_success_path.
    pub auth_success_value: Option<String>,
    /// Heartbeat interval in seconds.
    pub heartbeat_interval: Option<u64>,
    /// Heartbeat frame (JSON string).
    pub heartbeat_frame: Option<String>,

    // -- Inbound message parsing (both modes) --
    /// JSON path to filter which frames/posts are messages (e.g. "$.type").
    pub filter_path: Option<String>,
    /// Expected value at filter_path (e.g. "message").
    pub filter_value: Option<String>,
    /// JSON path to extract message text.
    pub text_path: Option<String>,
    /// JSON path to extract sender ID.
    pub sender_path: Option<String>,
    /// JSON path to extract group/chat ID (if present = group message).
    pub group_path: Option<String>,

    // -- Outbound reply --
    /// For webhook: HTTP callback URL for replies.
    pub reply_url: Option<String>,
    /// HTTP method for reply (default: POST).
    pub reply_method: Option<String>,
    /// Reply body template with {{sender}}, {{chat_id}}, {{reply}}, {{is_group}} placeholders.
    pub reply_template: Option<String>,
    /// Extra headers for reply HTTP call.
    pub reply_headers: Option<HashMap<String, String>>,
    /// For websocket: reply frame template (same placeholders).
    pub reply_frame: Option<String>,
}

// --- LINE Messaging API ---

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LineConfig {
    #[serde(flatten)]
    pub base: ChannelBase,
    pub channel_access_token: Option<SecretOrString>,
    pub channel_secret: Option<SecretOrString>,
    /// REST API base URL override (for testing). Defaults to https://api.line.me/v2/bot
    pub api_base: Option<String>,
    pub accounts: Option<HashMap<String, Value>>,
}

// --- Zalo Official Account API ---

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ZaloConfig {
    #[serde(flatten)]
    pub base: ChannelBase,
    pub access_token: Option<SecretOrString>,
    pub oa_secret: Option<SecretOrString>,
    /// REST API base URL override (for testing). Defaults to https://openapi.zalo.me/v3.0/oa
    pub api_base: Option<String>,
    pub accounts: Option<HashMap<String, Value>>,
}

// --- Matrix (Element) ---

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MatrixConfig {
    #[serde(flatten)]
    pub base: ChannelBase,
    pub homeserver: Option<String>,
    pub access_token: Option<SecretOrString>,
    pub user_id: Option<String>,
    pub device_id: Option<String>,
    pub recovery_key: Option<SecretOrString>,
    pub accounts: Option<HashMap<String, Value>>,
}

// --- QQ Official Bot (QQ机器人开放平台) ---

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct QQBotConfig {
    #[serde(flatten)]
    pub base: ChannelBase,
    pub app_id: Option<String>,
    pub app_secret: Option<SecretOrString>,
    /// Use sandbox API endpoint (default: false).
    pub sandbox: Option<bool>,
    /// Intent bits to subscribe. Default covers group @bot + C2C + guild.
    pub intents: Option<u32>,
    /// REST API base URL override (for testing). Defaults to https://api.sgroup.qq.com
    pub api_base: Option<String>,
    /// Token endpoint URL override (for testing). Defaults to https://bots.qq.com/app/getAppAccessToken
    pub token_url: Option<String>,
    pub accounts: Option<HashMap<String, Value>>,
}

// --- Personal WeChat (个人微信 via ilink) ---

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WeChatPersonalConfig {
    #[serde(flatten)]
    pub base: ChannelBase,
    /// Saved bot_token from QR login (auto-populated after `channels login
    /// --channel wechat`)
    pub bot_token: Option<SecretOrString>,
    /// Override the ilink API base URL (default: https://ilinkai.weixin.qq.com).
    /// Useful for testing with a mock server.
    pub base_url: Option<String>,
    pub accounts: Option<HashMap<String, Value>>,
}

/// Fields shared by every channel.
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ChannelBase {
    pub enabled: Option<bool>,
    pub dm_policy: Option<DmPolicy>,
    pub allow_from: Option<Vec<String>>,
    pub group_policy: Option<GroupPolicy>,
    pub group_allow_from: Option<Vec<String>>,
    pub health_monitor: Option<HealthMonitorConfig>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum DmPolicy {
    Pairing,
    Allowlist,
    Open,
    Disabled,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum GroupPolicy {
    Allowlist,
    Open,
    Disabled,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HealthMonitorConfig {
    pub enabled: Option<bool>,
    pub check_interval_min: Option<u32>,
}

// --- Telegram ---

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TelegramConfig {
    #[serde(flatten)]
    pub base: ChannelBase,
    pub bot_token: Option<SecretOrString>,
    pub token_file: Option<String>,
    pub history_limit: Option<u32>,
    pub reply_to_mode: Option<ReplyToMode>,
    pub link_preview: Option<bool>,
    pub streaming: Option<StreamingMode>,
    pub text_chunk_limit: Option<usize>,
    pub media_max_mb: Option<u32>,
    pub actions: Option<Value>,
    pub reaction_notifications: Option<ReactionNotif>,
    pub custom_commands: Option<Vec<BotCommand>>,
    pub groups: Option<HashMap<String, Value>>,
    pub proxy: Option<String>,
    pub webhook_url: Option<String>,
    pub webhook_secret: Option<SecretOrString>,
    pub webhook_path: Option<String>,
    pub network: Option<Value>,
    pub retry: Option<RetryConfig>,
    pub config_writes: Option<bool>,
    pub default_account: Option<String>,
    pub accounts: Option<HashMap<String, Value>>,
    pub api_base: Option<String>,
}

// --- Discord ---

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DiscordConfig {
    #[serde(flatten)]
    pub base: ChannelBase,
    pub token: Option<SecretOrString>,
    pub media_max_mb: Option<u32>,
    pub allow_bots: Option<bool>,
    pub streaming: Option<StreamingMode>,
    pub reply_to_mode: Option<ReplyToMode>,
    pub max_lines_per_message: Option<u32>,
    pub actions: Option<Value>,
    pub reaction_notifications: Option<ReactionNotif>,
    pub dm: Option<Value>,
    pub guilds: Option<HashMap<String, Value>>,
    pub accounts: Option<HashMap<String, Value>>,
    pub retry: Option<RetryConfig>,
    /// Gateway WebSocket URL override (for testing). Defaults to wss://gateway.discord.gg/?v=10&encoding=json
    pub gateway_url: Option<String>,
    /// HTTP API base URL override (for testing). Defaults to https://discord.com/api/v10
    pub api_base: Option<String>,
}

// --- Slack ---

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SlackConfig {
    #[serde(flatten)]
    pub base: ChannelBase,
    pub bot_token: Option<SecretOrString>,
    pub app_token: Option<SecretOrString>,
    /// Override the Slack API base URL (default: https://slack.com/api).
    /// Useful for pointing at a mock server during testing.
    pub api_base: Option<String>,
    pub streaming: Option<StreamingMode>,
    pub native_streaming: Option<bool>,
    pub text_chunk_limit: Option<usize>,
    pub media_max_mb: Option<u32>,
    pub workspaces: Option<HashMap<String, Value>>,
    pub retry: Option<RetryConfig>,
    pub accounts: Option<HashMap<String, Value>>,
}

// --- WhatsApp ---

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WhatsAppConfig {
    #[serde(flatten)]
    pub base: ChannelBase,
    pub text_chunk_limit: Option<usize>,
    pub chunk_mode: Option<ChunkMode>,
    pub media_max_mb: Option<u32>,
    pub send_read_receipts: Option<bool>,
    pub groups: Option<HashMap<String, Value>>,
    pub default_account: Option<String>,
    pub accounts: Option<HashMap<String, Value>>,
    pub retry: Option<RetryConfig>,
    /// REST API base URL override (for testing). Defaults to https://graph.facebook.com/v19.0
    pub api_base: Option<String>,
}

// --- Signal ---

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SignalConfig {
    #[serde(flatten)]
    pub base: ChannelBase,
    pub phone: Option<String>,
    pub text_chunk_limit: Option<usize>,
    pub retry: Option<RetryConfig>,
    /// Path to signal-cli binary (default: "signal-cli"). Can point to a mock script.
    pub cli_path: Option<String>,
    pub accounts: Option<HashMap<String, Value>>,
}

// --- iMessage ---

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IMessageConfig {
    #[serde(flatten)]
    pub base: ChannelBase,
    pub server_url: Option<String>,
    pub api_key: Option<SecretOrString>,
    pub retry: Option<RetryConfig>,
    pub accounts: Option<HashMap<String, Value>>,
}

// --- Mattermost ---

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MattermostConfig {
    #[serde(flatten)]
    pub base: ChannelBase,
    pub server_url: Option<String>,
    pub bot_token: Option<SecretOrString>,
    pub retry: Option<RetryConfig>,
    pub accounts: Option<HashMap<String, Value>>,
}

// --- MS Teams ---

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MSTeamsConfig {
    #[serde(flatten)]
    pub base: ChannelBase,
    pub tenant_id: Option<String>,
    pub client_id: Option<String>,
    pub client_secret: Option<SecretOrString>,
    pub retry: Option<RetryConfig>,
    pub accounts: Option<HashMap<String, Value>>,
}

// --- Google Chat ---

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GoogleChatConfig {
    #[serde(flatten)]
    pub base: ChannelBase,
    pub service_account_key_file: Option<String>,
    pub retry: Option<RetryConfig>,
    pub accounts: Option<HashMap<String, Value>>,
}

// --- Feishu (Lark) ---

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FeishuConfig {
    #[serde(flatten)]
    pub base: ChannelBase,
    pub app_id: Option<String>,
    pub app_secret: Option<SecretOrString>,
    pub verification_token: Option<SecretOrString>,
    pub encrypt_key: Option<SecretOrString>,
    pub streaming: Option<StreamingMode>,
    /// "feishu" (default, China) or "lark" (international)
    pub brand: Option<String>,
    /// REST API base URL override (for testing). Defaults to https://open.feishu.cn/open-apis
    pub api_base: Option<String>,
    /// WS endpoint request domain override (for testing). Defaults to https://open.feishu.cn
    pub ws_url: Option<String>,
    pub accounts: Option<HashMap<String, Value>>,
}

// --- DingTalk ---

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DingTalkConfig {
    #[serde(flatten)]
    pub base: ChannelBase,
    pub app_key: Option<String>,
    pub app_secret: Option<SecretOrString>,
    pub robot_code: Option<String>,
    pub streaming: Option<StreamingMode>,
    /// API base URL override (for testing). Defaults to https://api.dingtalk.com
    pub api_base: Option<String>,
    /// Old API base URL override. Defaults to https://oapi.dingtalk.com
    pub oapi_base: Option<String>,
    pub accounts: Option<HashMap<String, Value>>,
}

// --- WeCom (企业微信) ---

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WeComConfig {
    #[serde(flatten)]
    pub base: ChannelBase,
    /// Bot ID (企业微信后台显示)
    pub bot_id: Option<String>,
    /// Bot secret (企业微信后台显示)
    pub secret: Option<SecretOrString>,
    pub token: Option<SecretOrString>,
    pub encoding_aes_key: Option<SecretOrString>,
    pub streaming: Option<StreamingMode>,
    /// WebSocket URL override (defaults to wss://openws.work.weixin.qq.com)
    #[serde(alias = "wsUrl")]
    pub ws_url: Option<String>,
    pub accounts: Option<HashMap<String, Value>>,
}

// --- Shared channel enums / structs ---

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum ReplyToMode {
    Off,
    First,
    All,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum StreamingMode {
    Off,
    Partial,
    Block,
    Progress,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum ReactionNotif {
    Off,
    Own,
    All,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum ChunkMode {
    Length,
    Newline,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BotCommand {
    pub command: String,
    pub description: String,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RetryConfig {
    pub attempts: Option<u32>,
    pub min_delay_ms: Option<u64>,
    pub max_delay_ms: Option<u64>,
    pub jitter: Option<f64>,
}

// ---------------------------------------------------------------------------
// session
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionConfig {
    pub dm_scope: Option<DmScope>,
    pub thread_bindings: Option<Value>,
    pub reset: Option<SessionResetConfig>,
    pub identity_links: Option<HashMap<String, Vec<String>>>,
    pub maintenance: Option<SessionMaintenanceConfig>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum DmScope {
    Main,
    #[serde(rename = "per-peer")]
    PerPeer,
    #[serde(rename = "per-channel-peer")]
    PerChannelPeer,
    #[serde(rename = "per-account-channel-peer")]
    PerAccountChannelPeer,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionResetConfig {
    pub command: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionMaintenanceConfig {
    pub prune_after: Option<String>,
    pub max_entries: Option<u32>,
    pub max_disk_bytes: Option<u64>,
    pub rotate_bytes: Option<u64>,
    pub reset_archive_retention: Option<String>,
}

// ---------------------------------------------------------------------------
// bindings
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BindingConfig {
    #[serde(rename = "type")]
    pub kind: Option<String>,
    pub agent_id: String,
    #[serde(rename = "match")]
    pub match_: BindingMatch,
    pub priority: Option<i32>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BindingMatch {
    pub channel: Option<String>,
    pub peer_id: Option<String>,
    pub group_id: Option<String>,
    pub account_id: Option<String>,
    pub path: Option<String>,
}

// ---------------------------------------------------------------------------
// cron
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CronConfig {
    pub enabled: Option<bool>,
    pub max_concurrent_runs: Option<u32>,
    pub session_retention: Option<Value>,
    pub run_log: Option<RunLogConfig>,
    pub jobs: Option<Vec<CronJobConfig>>,
    /// Default delivery target for jobs without explicit delivery config.
    /// Jobs can override this by setting their own `delivery` field.
    pub default_delivery: Option<CronDelivery>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RunLogConfig {
    pub enabled: Option<bool>,
    pub max_runs: Option<u32>,
    pub retention: Option<String>,
}

/// Delivery target for cron job notifications (OpenClaw compat).
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct CronDelivery {
    /// Delivery mode: "announce" sends to channel, "none" disables.
    #[serde(default)]
    pub mode: Option<String>,
    /// Channel to send to: "feishu", "wechat", "telegram", etc.
    pub channel: Option<String>,
    /// Target user/chat ID.
    #[serde(rename = "to")]
    pub to: Option<String>,
    /// Thread/topic ID for channels that support it.
    pub thread_id: Option<String>,
    /// Account ID for multi-account setups.
    pub account_id: Option<String>,
    /// If true, silently ignore delivery failures.
    #[serde(default)]
    pub best_effort: Option<bool>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CronJobConfig {
    pub id: String,
    #[serde(default)]
    pub name: Option<String>,
    pub schedule: String,
    #[serde(default)]
    pub tz: Option<String>,
    pub agent_id: Option<String>,
    pub message: String,
    pub session: Option<Value>,
    pub enabled: Option<bool>,
    /// Delivery target for notifications when job completes.
    pub delivery: Option<CronDelivery>,
}

// ---------------------------------------------------------------------------
// tools
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolsConfig {
    pub loop_detection: Option<LoopDetectionConfig>,
    pub deny: Option<Vec<String>>,
    pub allow: Option<Vec<String>>,
    pub exec: Option<ExecToolConfig>,
    pub web_search: Option<WebSearchConfig>,
    pub web_fetch: Option<WebFetchConfig>,
    pub web_browser: Option<WebBrowserConfig>,
    pub computer_use: Option<ComputerUseConfig>,
    pub upload: Option<UploadConfig>,
    /// Max chars to keep in session history per tool result.
    /// Prevents session bloat from large web_fetch/web_search results.
    pub session_result_limits: Option<SessionResultLimits>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionResultLimits {
    /// web_search result max chars in session (default: 2000)
    pub web_search: Option<usize>,
    /// web_fetch result max chars in session (default: 5000)
    pub web_fetch: Option<usize>,
    /// web_browser snapshot/action max chars in session (default: 1500)
    /// Browser snapshots are large but mostly ephemeral (refs expire after page change).
    pub web_browser: Option<usize>,
    /// exec result max chars in session (default: 3000)
    pub exec: Option<usize>,
    /// Default for all other tools (default: 3000)
    pub default: Option<usize>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UploadConfig {
    /// Max file size before first confirmation (bytes, default 50MB)
    pub max_file_size: Option<usize>,
    /// Max text chars before token confirmation (default 20000)
    pub max_text_chars: Option<usize>,
    /// Whether current model supports vision/images
    pub supports_vision: Option<bool>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecToolConfig {
    /// Enable exec safety rules (default: false for openclaw compat).
    pub safety: Option<bool>,
    /// Timeout for exec commands in seconds (default: 1800 = 30 minutes).
    /// Matches openclaw's defaultTimeoutSec.
    pub timeout_seconds: Option<u64>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WebSearchConfig {
    /// Default search provider: "duckduckgo" | "google" | "bing" | "brave" | "serper"
    pub provider: Option<String>,
    /// API keys (alternative to env vars)
    pub brave_api_key: Option<SecretOrString>,
    pub google_api_key: Option<SecretOrString>,
    pub google_cx: Option<String>,
    pub bing_api_key: Option<SecretOrString>,
    /// Serper.dev API key for Google search results
    pub serper_api_key: Option<SecretOrString>,
    /// Max results per search (default: 5)
    pub max_results: Option<usize>,
    /// Disable web_search tool entirely
    pub enabled: Option<bool>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WebFetchConfig {
    pub enabled: Option<bool>,
    /// Max content length in chars (default: 100000)
    pub max_length: Option<usize>,
    /// Custom User-Agent
    pub user_agent: Option<String>,
    /// Model for content summarization (e.g. "doubao-lite"). If set and
    /// the agent passes a `prompt`, fetched content is summarized by this model.
    pub summary_model: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WebBrowserConfig {
    pub enabled: Option<bool>,
    /// Path to Chrome/Chromium binary (auto-detect if not set)
    pub chrome_path: Option<String>,
    /// Run browser with visible window (default: false = headless)
    pub headed: Option<bool>,
    /// Chrome profile to use. "default" = system default profile,
    /// other string = named profile directory under ~/.rsclaw/browser-profiles/.
    /// If not set, uses a temporary profile (no cookies/history).
    pub profile: Option<String>,
    /// Ports to probe for existing Chrome with remote debugging (default: [9222, 9223]).
    pub remote_debug_ports: Option<Vec<u16>>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ComputerUseConfig {
    pub enabled: Option<bool>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LoopDetectionConfig {
    pub enabled: Option<bool>,
    pub window: Option<usize>,
    pub threshold: Option<usize>,
    pub overrides: Option<std::collections::HashMap<String, usize>>,
}

// ---------------------------------------------------------------------------
// sandbox (top-level)
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SandboxConfig {
    pub mode: Option<SandboxMode>,
    pub scope: Option<SandboxScope>,
    pub docker: Option<DockerConfig>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum SandboxMode {
    Off,
    #[serde(rename = "non-main")]
    NonMain,
    All,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum SandboxScope {
    Session,
    Agent,
    Shared,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DockerConfig {
    pub image: Option<String>,
    pub network: Option<String>,
    pub mounts: Option<Vec<String>>,
}

// ---------------------------------------------------------------------------
// logging
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LoggingConfig {
    pub level: Option<String>,
    pub format: Option<LogFormat>,
    pub file: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum LogFormat {
    Pretty,
    Json,
    Compact,
}

// ---------------------------------------------------------------------------
// skills
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SkillsConfig {
    pub install: Option<SkillInstallConfig>,
    pub entries: Option<HashMap<String, SkillEntryConfig>>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SkillInstallConfig {
    pub directory: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SkillEntryConfig {
    pub enabled: Option<bool>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

// ---------------------------------------------------------------------------
// plugins
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginsConfig {
    pub entries: Option<HashMap<String, PluginEntryConfig>>,
    pub slots: Option<PluginSlots>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginEntryConfig {
    pub enabled: Option<bool>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginSlots {
    pub memory: Option<String>,
    pub context_engine: Option<String>,
}

// ---------------------------------------------------------------------------
// hooks
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HooksConfig {
    pub enabled: bool,
    pub token: Option<SecretOrString>,
    pub path: Option<String>,
    pub default_session_key: Option<String>,
    pub allow_request_session_key: Option<bool>,
    pub allowed_session_key_prefixes: Option<Vec<String>>,
    pub mappings: Option<Vec<HookMapping>>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HookMapping {
    #[serde(rename = "match")]
    pub match_: HookMatch,
    pub action: HookAction,
    pub agent_id: Option<String>,
    pub session_key: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HookMatch {
    pub path: Option<String>,
    pub method: Option<String>,
    pub headers: Option<HashMap<String, String>>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum HookAction {
    Agent,
    Script,
}

// ---------------------------------------------------------------------------
// secrets
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SecretsConfig {
    pub providers: HashMap<String, SecretProviderConfig>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SecretProviderConfig {
    #[serde(rename = "type")]
    pub kind: SecretProviderKind,
    pub command: Option<String>,
    pub args: Option<Vec<String>>,
    pub file: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum SecretProviderKind {
    Env,
    File,
    Exec,
}

// ---------------------------------------------------------------------------
// memory
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MemoryConfig {
    pub enabled: Option<bool>,
    pub backend: Option<MemoryBackend>,
    pub auto_capture: Option<bool>,
    pub auto_recall: Option<bool>,
    pub retrieval: Option<Value>,
    pub enable_management_tools: Option<bool>,
    pub scope: Option<ScopeConfig>,
    /// Number of results to retrieve per search backend (vector / BM25)
    /// before RRF fusion. Default 10 (was 5).
    pub recall_top_k: Option<usize>,
    /// Number of final results after RRF fusion. Default 5.
    pub recall_final_k: Option<usize>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum MemoryBackend {
    LanceDb,
    None,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ScopeConfig {
    pub default: Option<String>,
    pub definitions: Option<HashMap<String, Value>>,
    pub agent_access: Option<HashMap<String, Vec<String>>>,
}

// ---------------------------------------------------------------------------
// Shared primitives
// ---------------------------------------------------------------------------

/// A value that is either a plain string or a SecretRef object.
///
/// ```json5
/// // Plain string (not recommended for secrets)
/// { apiKey: "sk-..." }
///
/// // SecretRef
/// { apiKey: { source: "env", provider: "default", id: "OPENAI_API_KEY" } }
/// ```
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum SecretOrString {
    Plain(String),
    Ref(SecretRef),
}

impl SecretOrString {
    /// Return the plain string value if this is not a SecretRef.
    /// For SecretRef variants, resolution happens in `SecretsManager`.
    pub fn as_plain(&self) -> Option<&str> {
        match self {
            SecretOrString::Plain(s) => Some(s.as_str()),
            SecretOrString::Ref(_) => None,
        }
    }

    /// Resolve eagerly without a full `RuntimeConfig`.
    /// - `Plain` → returns the string as-is.
    /// - `Ref { source: Env, id }` → calls `std::env::var(id)`.
    /// - `Ref { source: File | Exec, .. }` → returns `None` (needs
    ///   `SecretsManager`).
    pub fn resolve_early(&self) -> Option<String> {
        match self {
            SecretOrString::Plain(s) => {
                // Support ${VAR} syntax in plain strings.
                let expanded = crate::config::loader::expand_env_vars(s);
                Some(expanded)
            }
            SecretOrString::Ref(r) if r.source == SecretSource::Env => std::env::var(&r.id).ok(),
            SecretOrString::Ref(_) => None,
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SecretRef {
    pub source: SecretSource,
    pub provider: Option<String>,
    pub id: String,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum SecretSource {
    Env,
    File,
    Exec,
}

// ---------------------------------------------------------------------------
// memorySearch (OpenClaw-compatible embedding configuration)
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MemorySearchConfig {
    /// Embedding provider: "openai", "gemini", "voyage", "ollama", "local"
    pub provider: Option<String>,
    /// Embedding model name, e.g. "text-embedding-3-small"
    pub model: Option<String>,
    /// What to index: ["memory", "sessions"]
    pub sources: Option<Vec<String>>,
    /// Custom base URL for the embedding API
    pub base_url: Option<String>,
    /// API key (plain or SecretRef) for the embedding service
    pub api_key: Option<SecretOrString>,
    /// Local model settings
    pub local: Option<LocalEmbeddingConfig>,
    /// Experimental flags
    pub experimental: Option<Value>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LocalEmbeddingConfig {
    /// Path to a GGUF model file for local embedding
    pub model_path: Option<String>,
    /// Override HuggingFace download URL for the embedding model.
    /// Default: auto-detect based on locale (hf-mirror.com for zh, huggingface.co otherwise).
    pub model_download_url: Option<String>,
    /// Model repo name on HuggingFace (default: "BAAI/bge-small-zh-v1.5")
    pub model_repo: Option<String>,
}

// ---------------------------------------------------------------------------
// memory (top-level, separate from memorySearch)
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MemoryTopConfig {
    pub enabled: Option<bool>,
    pub provider: Option<String>,
    pub search: Option<MemoryTopSearchConfig>,
    /// Per-backend recall count before RRF fusion (default 10).
    pub recall_top_k: Option<usize>,
    /// Final results after RRF fusion + reranking (default 5).
    pub recall_final_k: Option<usize>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MemoryTopSearchConfig {
    pub model: Option<String>,
    pub max_results: Option<u32>,
}

// ---------------------------------------------------------------------------
// mcp (Model Context Protocol servers)
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct McpConfig {
    pub enabled: Option<bool>,
    pub servers: Option<Vec<McpServerConfig>>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct McpServerConfig {
    pub name: String,
    pub command: String,
    pub args: Option<Vec<String>>,
    pub env: Option<HashMap<String, String>>,
}

// ---------------------------------------------------------------------------
// messages
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MessagesConfig {
    pub prefix: Option<String>,
    pub ack_reaction: Option<String>,
    pub ack_reaction_scope: Option<String>,
    pub inbound_debounce: Option<DebounceConfig>,
    pub compaction: Option<MsgCompactionConfig>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DebounceConfig {
    pub enabled: Option<bool>,
    pub window: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MsgCompactionConfig {
    pub enabled: Option<bool>,
    pub token_threshold: Option<u32>,
}

// ---------------------------------------------------------------------------
// commands
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CommandsConfig {
    pub enabled: Option<bool>,
    pub native: Option<String>,
    pub native_skills: Option<String>,
    pub restart: Option<bool>,
    pub owner_display: Option<String>,
    pub prefix: Option<String>,
    pub list: Option<Vec<Value>>,
}

// ---------------------------------------------------------------------------
// cli
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CliConfig {
    pub banner: Option<bool>,
    pub backend: Option<String>,
}

// ---------------------------------------------------------------------------
// browser
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BrowserConfig {
    pub enable_cdp: Option<bool>,
    pub headless: Option<bool>,
    pub user_agent: Option<String>,
}

// ---------------------------------------------------------------------------
// ui
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UiConfig {
    pub theme: Option<String>,
    pub assistant_name: Option<String>,
    pub assistant_emoji: Option<String>,
}

// ---------------------------------------------------------------------------
// approvals
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApprovalsConfig {
    pub exec: Option<ExecApprovalConfig>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecApprovalConfig {
    pub enabled: Option<bool>,
    pub mode: Option<String>,
    pub agent_filter: Option<Vec<String>>,
    pub session_filter: Option<Vec<String>>,
    pub targets: Option<Vec<Value>>,
}

// ---------------------------------------------------------------------------
// canvasHost
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CanvasHostConfig {
    pub enabled: Option<bool>,
    pub port: Option<u16>,
    pub bind: Option<String>,
    pub root: Option<String>,
    pub live_reload: Option<bool>,
}

// ---------------------------------------------------------------------------
// talk (TTS)
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TalkConfig {
    pub enabled: Option<bool>,
    pub provider: Option<String>,
    pub voice: Option<String>,
    pub speed: Option<f64>,
    pub instructions: Option<String>,
    pub api_key: Option<SecretOrString>,
}

// ---------------------------------------------------------------------------
// web (control UI settings)
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WebConfig {
    pub port: Option<u16>,
    pub bind: Option<String>,
    pub tls_enabled: Option<bool>,
}