nexo-core 0.2.1

Agent runtime: event bus, sessions, plugin trait, heartbeat, A2A delegation.
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
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
//! `nexo/admin/llm_providers/*` handlers.
//!
//! Operates on `llm.yaml.providers.<id>`. Abstracted via
//! [`LlmYamlPatcher`] so this crate stays cycle-free vs
//! `nexo-setup`.

use serde_json::Value;

use async_trait::async_trait;
use nexo_tool_meta::admin::llm_providers::{
    AuthMode, CredentialFieldDescriptor, LlmProviderCatalogEntry, LlmProviderError,
    LlmProviderProbeDraftInput, LlmProviderProbeInput, LlmProviderProbeResponse,
    LlmProviderSummary, LlmProviderUpsertInput, LlmProvidersCatalogResponse,
    LlmProvidersDeleteParams, LlmProvidersDeleteResponse, LlmProvidersListResponse,
    OAuthFinishInput, OAuthFinishResponse, OAuthStartInput, OAuthStartResponse,
};

use super::agents::YamlPatcher;
use super::secrets::SecretsStore;
use crate::agent::admin_rpc::dispatcher::{AdminRpcError, AdminRpcResult};

/// Minimal schema lookup the upsert handler needs to
/// validate operator payloads against the factory the daemon has
/// registered. Production wraps a `nexo_llm::LlmRegistry`; tests can
/// inject an inline mock. Kept small + read-only so the handler
/// stays cycle-free vs `nexo-llm` while still being able to gate
/// every persistence step on the schema.
pub trait FactorySchemaLookup: Send + Sync {
    /// Returns the credential schema for `factory_id`, or `None` when
    /// the factory isn't registered. The handler maps `None` to
    /// `LlmProviderError::InvalidAuthMode { factory: factory_id, mode: "<unknown>" }`
    /// — operator picked a factory the daemon can't instantiate.
    fn credential_schema(&self, factory_id: &str) -> Option<Vec<CredentialFieldDescriptor>>;

    /// Returns the auth modes `factory_id` supports. Used to reject
    /// upsert / oauth_start with an unsupported mode early.
    fn supported_auth_modes(&self, factory_id: &str) -> Option<Vec<AuthMode>>;
}

/// Derive a valid `SecretsStore` name from an
/// LLM provider instance id. The store enforces
/// `^[A-Z][A-Z0-9_]{1,63}$`, but instance ids are lowercase slugs
/// (e.g. `minimax-cliente-a`). Transform: prefix `LLM_`, uppercase,
/// replace any non-alnum with `_`. Keeps the mapping deterministic
/// + reversible for diagnostics.
pub fn secret_id_for_instance(instance_id: &str) -> String {
    let mut out = String::with_capacity(4 + instance_id.len());
    out.push_str("LLM_");
    for c in instance_id.chars() {
        if c.is_ascii_alphanumeric() {
            out.push(c.to_ascii_uppercase());
        } else {
            out.push('_');
        }
    }
    out
}

/// Yaml mutation surface for `llm.yaml`. Production wraps an
/// `nexo_setup::yaml_patch`-style adapter pointed at the LLM
/// config file.
pub trait LlmYamlPatcher: Send + Sync {
    /// List provider ids in source order.
    fn list_provider_ids(&self) -> anyhow::Result<Vec<String>>;
    /// Read a dotted field under `providers.<id>.*`.
    fn read_provider_field(&self, provider_id: &str, dotted: &str)
        -> anyhow::Result<Option<Value>>;
    /// Upsert a dotted field under `providers.<id>.*`.
    fn upsert_provider_field(
        &self,
        provider_id: &str,
        dotted: &str,
        value: Value,
    ) -> anyhow::Result<()>;
    /// Remove the entire `providers.<id>` block.
    fn remove_provider(&self, provider_id: &str) -> anyhow::Result<()>;

    /// List provider ids under
    /// `tenants.<tenant_id>.providers`. Empty when the tenant
    /// has no providers block (or the tenant doesn't exist).
    /// Default impl returns empty so legacy patchers without
    /// tenant support compile cleanly while behaving as if no
    /// tenant overrides existed.
    fn list_tenant_provider_ids(&self, _tenant_id: &str) -> anyhow::Result<Vec<String>> {
        Ok(Vec::new())
    }

    /// Read a dotted field under
    /// `tenants.<tenant_id>.providers.<provider_id>.*`.
    /// Default impl returns `None`.
    fn read_tenant_provider_field(
        &self,
        _tenant_id: &str,
        _provider_id: &str,
        _dotted: &str,
    ) -> anyhow::Result<Option<Value>> {
        Ok(None)
    }

    /// Upsert a dotted field under
    /// `tenants.<tenant_id>.providers.<provider_id>.*`.
    /// Default impl errors so unimplemented adapters surface
    /// the gap explicitly rather than silently no-op.
    fn upsert_tenant_provider_field(
        &self,
        _tenant_id: &str,
        _provider_id: &str,
        _dotted: &str,
        _value: Value,
    ) -> anyhow::Result<()> {
        Err(anyhow::anyhow!(
            "upsert_tenant_provider_field not implemented for this LlmYamlPatcher"
        ))
    }

    /// Remove the
    /// `tenants.<tenant_id>.providers.<provider_id>` block.
    fn remove_tenant_provider(&self, _tenant_id: &str, _provider_id: &str) -> anyhow::Result<()> {
        Err(anyhow::anyhow!(
            "remove_tenant_provider not implemented for this LlmYamlPatcher"
        ))
    }
}

/// `nexo/admin/llm_providers/catalog` — return the static metadata
/// for every LLM provider factory the daemon has registered. Pure
/// snapshot read; no yaml access. Operator UIs use this to render a
/// strict provider/model dropdown without keeping their own list.
pub fn catalog(catalog: &[LlmProviderCatalogEntry]) -> AdminRpcResult {
    AdminRpcResult::ok(
        serde_json::to_value(LlmProvidersCatalogResponse {
            providers: catalog.to_vec(),
        })
        .unwrap_or(Value::Null),
    )
}

/// `nexo/admin/llm_providers/list` — return all providers from
/// `llm.yaml`.
pub fn list(patcher: &dyn LlmYamlPatcher) -> AdminRpcResult {
    let ids = match patcher.list_provider_ids() {
        Ok(i) => i,
        Err(e) => {
            return AdminRpcResult::err(AdminRpcError::Internal(format!("llm.yaml read: {e}")));
        }
    };
    let mut providers: Vec<LlmProviderSummary> = ids
        .into_iter()
        .filter_map(|id| read_summary(patcher, &id).ok().flatten())
        .collect();
    providers.sort_by(|a, b| a.id.cmp(&b.id));
    AdminRpcResult::ok(
        serde_json::to_value(LlmProvidersListResponse { providers }).unwrap_or(Value::Null),
    )
}

/// `nexo/admin/llm_providers/upsert` — create or update a
/// provider block.
///
/// Two execution paths:
///
/// * **Schema-driven**: when `input.fields` is
///   non-empty, the handler resolves the factory's
///   `credential_schema` via `factory_schema`, validates the
///   payload, then persists each field — `secret == true` to the
///   SecretsStore, others inline in yaml. Triggered by the
///   microapp wizard.
/// * **Legacy**: when `input.fields` is empty,
///   falls back to the api_key_env / api_key_secret_id /
///   api_key_secret_value path (exactly-one-source rule). Existing
///   older microapps keep working unchanged.
pub async fn upsert(
    patcher: &dyn LlmYamlPatcher,
    secrets: Option<&dyn SecretsStore>,
    factory_schema: Option<&dyn FactorySchemaLookup>,
    params: Value,
    reload_signal: &(dyn Fn() + Send + Sync),
) -> AdminRpcResult {
    let input: LlmProviderUpsertInput = match serde_json::from_value(params) {
        Ok(i) => i,
        Err(e) => return AdminRpcResult::err(AdminRpcError::InvalidParams(e.to_string())),
    };
    if input.id.is_empty() {
        return AdminRpcResult::err(AdminRpcError::InvalidParams("id is empty".into()));
    }
    if input.base_url.is_empty() {
        return AdminRpcResult::err(AdminRpcError::InvalidParams("base_url is empty".into()));
    }

    // OAuth bypass. When the operator has already
    // run `oauth_finish` (which persisted the bundle to the
    // SecretsStore + patched yaml `auth.mode = oauth_bundle,
    // auth.bundle = <path>`), the subsequent `upsert` call only
    // needs to stamp `base_url + factory_type` on the yaml. Skip
    // both the schema-driven validation AND the legacy
    // exactly-one-key-source rule — bundle owns the credentials.
    //
    // Order matters: the bypass runs FIRST so any stray `fields`
    // payload (e.g. older microapp versions stamping
    // `oauth_bundle_secret_id` for tracking) doesn't trip the
    // schema validator's UNKNOWN_FIELD check. Defensive against
    // stale frontend deployments.
    let oauth_mode = matches!(
        input.auth_mode,
        Some(AuthMode::OAuthAuthCode)
            | Some(AuthMode::OAuthDeviceCode)
            | Some(AuthMode::OAuthBundleImport)
    );
    if oauth_mode {
        let _ = factory_schema; // schema not consulted in OAuth path
        let _ = secrets; // bundle persistence already done by oauth_finish
        return upsert_oauth_metadata(patcher, input, reload_signal);
    }

    // Schema-driven path when the operator
    // submitted a non-OAuth `fields` payload. Legacy path stays
    // intact for callers that still use api_key_env etc.
    if !input.fields.is_empty() {
        return upsert_schema_driven(patcher, secrets, factory_schema, input, reload_signal).await;
    }
    let _ = factory_schema; // silence unused when fields empty

    // Exactly-one-key-source rule. Caller must
    // pick a SINGLE path:
    //   * api_key_env (legacy, deprecated): name of an env var
    //     already exported in the daemon process.
    //   * api_key_secret_id: name of a pre-written secret in the
    //     SecretsStore (write it via secrets/write first).
    //   * api_key_secret_value: write-through.
    // Refuse mixed sources loud — operator intent must be explicit.
    let env_set = !input.api_key_env.is_empty();
    let secret_id_set = input
        .api_key_secret_id
        .as_deref()
        .map(|s| !s.is_empty())
        .unwrap_or(false);
    let secret_value_set = input
        .api_key_secret_value
        .as_deref()
        .map(|s| !s.is_empty())
        .unwrap_or(false);
    let source_count =
        usize::from(env_set) + usize::from(secret_id_set) + usize::from(secret_value_set);
    if source_count == 0 {
        return AdminRpcResult::err(AdminRpcError::InvalidParams(
            "exactly one API key source required: api_key_env, api_key_secret_id, or api_key_secret_value".into(),
        ));
    }
    if source_count > 1 {
        return AdminRpcResult::err(AdminRpcError::InvalidParams(
            "conflicting API key sources: pick exactly ONE of api_key_env, api_key_secret_id, api_key_secret_value".into(),
        ));
    }
    // Write-through. Stamp the value into the
    // SecretsStore under a derived id (`LLM_<INSTANCE>`), then on
    // successful persist swap the in-memory input to point at the
    // secret_id so the rest of the handler treats it as the
    // pre-staged path. Atomic ordering: SECRET WRITE FIRST, yaml
    // second — if the yaml write fails the operator can retry
    // with the same value (idempotent overwrite) without leaking
    // a half-written provider block.
    let mut effective_secret_id: Option<String> = input.api_key_secret_id.clone();
    if secret_value_set {
        let store = match secrets {
            Some(s) => s,
            None => {
                return AdminRpcResult::err(AdminRpcError::Internal(
                    "secrets store not configured — cannot write api_key_secret_value".into(),
                ));
            }
        };
        let value = input.api_key_secret_value.as_deref().unwrap_or_default();
        let derived = secret_id_for_instance(&input.id);
        match store.write(&derived, value).await {
            Ok(_) => {
                effective_secret_id = Some(derived);
            }
            Err(e) => return AdminRpcResult::err(e),
        }
    }
    if env_set && std::env::var(&input.api_key_env).is_err() {
        return AdminRpcResult::err(AdminRpcError::InvalidParams(format!(
            "api_key_env `{}` is not set in process env",
            input.api_key_env
        )));
    }

    // Split the write path: tenant-scoped
    // upserts call `upsert_tenant_provider_field` (writes under
    // `tenants.<id>.providers.<provider_id>.*`); global upserts
    // call the legacy `upsert_provider_field` exactly as before.
    // Tenant id "" treated as None for defense-in-depth (caller
    // bug should not silently write to `tenants..providers.*`).
    let tenant_id = input
        .tenant_id
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string);

    let write_field = |dotted: &str, value: Value| -> anyhow::Result<()> {
        match tenant_id.as_deref() {
            Some(tid) => patcher.upsert_tenant_provider_field(tid, &input.id, dotted, value),
            None => patcher.upsert_provider_field(&input.id, dotted, value),
        }
    };

    if let Err(e) = write_field("base_url", Value::String(input.base_url.clone())) {
        return AdminRpcResult::err(AdminRpcError::Internal(format!("yaml write: {e}")));
    }
    // Persist factory_type when supplied so the
    // registry can split instance-id from factory-id at runtime.
    // Empty / None ⇒ skip the write so legacy yamls stay tidy
    // (factory_type field stays absent, instance id is the
    // factory id by fallback).
    if let Some(ft) = input
        .factory_type
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
    {
        if let Err(e) = write_field("factory_type", Value::String(ft.to_string())) {
            return AdminRpcResult::err(AdminRpcError::Internal(format!("yaml write: {e}")));
        }
    }
    // Write whichever single key source was
    // provided. The pre-validation above guaranteed exactly one is
    // set; we still defensively check before writing each.
    if env_set {
        if let Err(e) = write_field("api_key_env", Value::String(input.api_key_env.clone())) {
            return AdminRpcResult::err(AdminRpcError::Internal(format!("yaml write: {e}")));
        }
    }
    if let Some(sid) = effective_secret_id
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
    {
        if let Err(e) = write_field("api_key_secret_id", Value::String(sid.to_string())) {
            return AdminRpcResult::err(AdminRpcError::Internal(format!("yaml write: {e}")));
        }
    }
    if !input.headers.is_empty() {
        let map: serde_json::Map<String, Value> = input
            .headers
            .iter()
            .map(|(k, v)| (k.clone(), Value::String(v.clone())))
            .collect();
        if let Err(e) = write_field("headers", Value::Object(map)) {
            return AdminRpcResult::err(AdminRpcError::Internal(format!("yaml write: {e}")));
        }
    }
    reload_signal();

    let summary = LlmProviderSummary {
        id: input.id,
        base_url: input.base_url,
        api_key_env: input.api_key_env,
        tenant_scope: tenant_id,
    };
    AdminRpcResult::ok(serde_json::to_value(summary).unwrap_or(Value::Null))
}

/// OAuth metadata-only path. The operator has
/// already run `oauth_finish` which persisted the bundle to the
/// SecretsStore + patched yaml `auth.mode = oauth_bundle,
/// auth.bundle = <path>`. The follow-up `upsert` only stamps
/// `base_url + factory_type + auth.mode` so the operator's chosen
/// instance has a complete yaml block.
fn upsert_oauth_metadata(
    patcher: &dyn LlmYamlPatcher,
    input: LlmProviderUpsertInput,
    reload_signal: &(dyn Fn() + Send + Sync),
) -> AdminRpcResult {
    let tenant_id = input
        .tenant_id
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string);

    let write_field = |dotted: &str, value: Value| -> anyhow::Result<()> {
        match tenant_id.as_deref() {
            Some(tid) => patcher.upsert_tenant_provider_field(tid, &input.id, dotted, value),
            None => patcher.upsert_provider_field(&input.id, dotted, value),
        }
    };

    if let Err(e) = write_field("base_url", Value::String(input.base_url.clone())) {
        return err_typed(LlmProviderError::YamlWriteFailed {
            detail: e.to_string(),
        });
    }
    if let Some(ft) = input
        .factory_type
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
    {
        if let Err(e) = write_field("factory_type", Value::String(ft.to_string())) {
            return err_typed(LlmProviderError::YamlWriteFailed {
                detail: e.to_string(),
            });
        }
    }
    // The bundle path was already stamped by oauth_finish.
    // Setting auth.mode here is idempotent — it should already
    // match — but keep it for defense (e.g. operator switched
    // mode between oauth_finish and upsert).
    if let Some(mode) = input.auth_mode {
        let wire = auth_mode_wire(mode);
        // OAuthBundleImport persists as `oauth_bundle` upstream;
        // for the other OAuth variants, oauth_finish already
        // wrote `auth.mode = oauth_bundle`. Either way we mirror
        // that here.
        let yaml_mode = if matches!(
            mode,
            AuthMode::OAuthAuthCode | AuthMode::OAuthDeviceCode | AuthMode::OAuthBundleImport
        ) {
            "oauth_bundle"
        } else {
            wire
        };
        if let Err(e) = write_field("auth.mode", Value::String(yaml_mode.to_string())) {
            return err_typed(LlmProviderError::YamlWriteFailed {
                detail: e.to_string(),
            });
        }
    }
    reload_signal();

    let summary = LlmProviderSummary {
        id: input.id,
        base_url: input.base_url,
        api_key_env: String::new(),
        tenant_scope: tenant_id,
    };
    AdminRpcResult::ok(serde_json::to_value(summary).unwrap_or(Value::Null))
}

/// Schema-driven persistence path. Triggered when
/// `LlmProviderUpsertInput::fields` is non-empty. Validates the
/// payload against the factory's declared
/// [`CredentialFieldDescriptor`] schema before any disk write so
/// the SecretsStore + yaml never end up in a partial state from a
/// bad payload.
///
/// Order of operations:
///
/// 1. Resolve factory id (`factory_type` ?? instance id) +
///    schema lookup. Unknown factory ⇒
///    `LlmProviderError::InvalidAuthMode { mode: "<unknown>" }`.
/// 2. Validate `auth_mode` against
///    `factory.supported_auth_modes()`. Unsupported ⇒
///    `InvalidAuthMode`.
/// 3. Walk the operator's `fields`:
///    a. Each key MUST be in schema (else `UnknownField`).
///    b. If the descriptor has `depends_on` and it isn't
///       satisfied, the field is silently ignored (the SPA
///       shouldn't have shown it; defensive).
/// 4. Walk the schema:
///    a. Required fields whose `depends_on` is satisfied MUST be
///       present + non-empty (else `MissingField`).
///    b. Apply `validation` regex / length (else `InvalidFormat`).
/// 5. Persist:
///    a. `secret == true` fields → SecretsStore under
///       `LLM_<INSTANCE>_<NAME_UPPER>`. yaml gets a
///       `<name>_secret_id` reference.
///    b. `secret == false` fields → yaml inline at
///       `providers.<id>.<name>`.
/// 6. If `auth_mode != Some(ApiKey)` and not `None`, persist
///    yaml `auth.mode = <wire form>`.
/// 7. `reload_signal()`.
async fn upsert_schema_driven(
    patcher: &dyn LlmYamlPatcher,
    secrets: Option<&dyn SecretsStore>,
    factory_schema: Option<&dyn FactorySchemaLookup>,
    input: LlmProviderUpsertInput,
    reload_signal: &(dyn Fn() + Send + Sync),
) -> AdminRpcResult {
    // ── Step 1: resolve factory + schema ─────────────────────────
    let factory_id = input
        .factory_type
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .unwrap_or(input.id.as_str())
        .to_string();
    let lookup = match factory_schema {
        Some(l) => l,
        None => {
            return AdminRpcResult::err(AdminRpcError::Internal(
                "factory schema lookup not configured — cannot honour `fields` payload".into(),
            ));
        }
    };
    let schema = match lookup.credential_schema(&factory_id) {
        Some(s) => s,
        None => {
            return err_typed(LlmProviderError::InvalidAuthMode {
                factory: factory_id.clone(),
                mode: "<unknown factory>".into(),
            });
        }
    };

    // ── Step 2: auth_mode validation ─────────────────────────────
    if let Some(mode) = input.auth_mode {
        let supported = lookup.supported_auth_modes(&factory_id).unwrap_or_default();
        if !supported.contains(&mode) {
            return err_typed(LlmProviderError::InvalidAuthMode {
                factory: factory_id.clone(),
                mode: auth_mode_wire(mode).to_string(),
            });
        }
    }

    // ── Step 3: unknown / ignored field check ────────────────────
    for k in input.fields.keys() {
        if !schema.iter().any(|d| &d.name == k) {
            return err_typed(LlmProviderError::UnknownField { field: k.clone() });
        }
    }

    // ── Step 4: required + validation pass ───────────────────────
    for descriptor in &schema {
        let active = descriptor
            .depends_on
            .as_ref()
            .map(|d| d.satisfied(&input.fields))
            .unwrap_or(true);
        let value = input
            .fields
            .get(&descriptor.name)
            .map(String::as_str)
            .map(str::trim)
            .filter(|s| !s.is_empty());
        if descriptor.required && active && value.is_none() {
            return err_typed(LlmProviderError::MissingField {
                field: descriptor.name.clone(),
            });
        }
        if let (Some(v), Some(rule)) = (value, descriptor.validation.as_ref()) {
            if let Err(hint) = apply_validation(v, rule) {
                return err_typed(LlmProviderError::InvalidFormat {
                    field: descriptor.name.clone(),
                    hint,
                });
            }
        }
    }

    // ── Step 5: persistence ──────────────────────────────────────
    let tenant_id = input
        .tenant_id
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string);

    let write_field = |dotted: &str, value: Value| -> anyhow::Result<()> {
        match tenant_id.as_deref() {
            Some(tid) => patcher.upsert_tenant_provider_field(tid, &input.id, dotted, value),
            None => patcher.upsert_provider_field(&input.id, dotted, value),
        }
    };

    if let Err(e) = write_field("base_url", Value::String(input.base_url.clone())) {
        return err_typed(LlmProviderError::YamlWriteFailed {
            detail: e.to_string(),
        });
    }
    if let Some(ft) = input
        .factory_type
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
    {
        if let Err(e) = write_field("factory_type", Value::String(ft.to_string())) {
            return err_typed(LlmProviderError::YamlWriteFailed {
                detail: e.to_string(),
            });
        }
    }

    // Per-field persistence: secret → SecretsStore + yaml ref.
    // non-secret → yaml inline. depends_on-inactive fields are
    // skipped (SPA shouldn't have submitted them; if it did,
    // dropping them is the safe choice).
    for descriptor in &schema {
        let active = descriptor
            .depends_on
            .as_ref()
            .map(|d| d.satisfied(&input.fields))
            .unwrap_or(true);
        if !active {
            continue;
        }
        let Some(value) = input
            .fields
            .get(&descriptor.name)
            .map(String::as_str)
            .map(str::trim)
            .filter(|s| !s.is_empty())
        else {
            continue;
        };

        if descriptor.secret {
            let store = match secrets {
                Some(s) => s,
                None => {
                    return AdminRpcResult::err(AdminRpcError::Internal(format!(
                        "secrets store not configured — cannot persist secret field `{}`",
                        descriptor.name
                    )));
                }
            };
            let derived = secret_id_for_field(&input.id, &descriptor.name);
            if let Err(e) = store.write(&derived, value).await {
                return err_typed(LlmProviderError::SecretWriteFailed {
                    detail: e.to_string(),
                });
            }
            let yaml_key = format!("{}_secret_id", descriptor.name);
            if let Err(e) = write_field(&yaml_key, Value::String(derived)) {
                return err_typed(LlmProviderError::YamlWriteFailed {
                    detail: e.to_string(),
                });
            }
        } else if let Err(e) = write_field(&descriptor.name, Value::String(value.to_string())) {
            return err_typed(LlmProviderError::YamlWriteFailed {
                detail: e.to_string(),
            });
        }
    }

    // ── Step 6: persist auth.mode when explicit + non-default ────
    if let Some(mode) = input.auth_mode {
        if mode != AuthMode::ApiKey {
            if let Err(e) =
                write_field("auth.mode", Value::String(auth_mode_wire(mode).to_string()))
            {
                return err_typed(LlmProviderError::YamlWriteFailed {
                    detail: e.to_string(),
                });
            }
        }
    }

    // ── Step 7: reload + summary ─────────────────────────────────
    reload_signal();
    let summary = LlmProviderSummary {
        id: input.id,
        base_url: input.base_url,
        api_key_env: String::new(),
        tenant_scope: tenant_id,
    };
    AdminRpcResult::ok(serde_json::to_value(summary).unwrap_or(Value::Null))
}

/// Derive a per-field secret id from
/// `(instance_id, field_name)`. Combines the instance-id transform
/// (`secret_id_for_instance`) with the field name to produce e.g.
/// `LLM_MINIMAX_CLIENTE_A_API_KEY`. Deterministic + reversible.
fn secret_id_for_field(instance_id: &str, field_name: &str) -> String {
    let mut out = secret_id_for_instance(instance_id);
    out.push('_');
    for c in field_name.chars() {
        if c.is_ascii_alphanumeric() {
            out.push(c.to_ascii_uppercase());
        } else {
            out.push('_');
        }
    }
    out
}

/// Apply a `FieldValidation` rule to a value. Returns the operator-
/// facing hint on failure.
fn apply_validation(
    value: &str,
    rule: &nexo_tool_meta::admin::llm_providers::FieldValidation,
) -> Result<(), String> {
    use nexo_tool_meta::admin::llm_providers::FieldValidation;
    match rule {
        FieldValidation::Regex { pattern, hint } => {
            // Best-effort compile. A bad regex from a factory is a
            // bug; we treat it as "no validation" rather than
            // crashing the dispatch.
            match regex::Regex::new(pattern) {
                Ok(re) if re.is_match(value) => Ok(()),
                Ok(_) => Err(hint.clone()),
                Err(_) => Ok(()),
            }
        }
        FieldValidation::Length { min, max } => {
            let n = value.chars().count();
            if n < *min || n > *max {
                Err(format!("length {n} not in [{min}, {max}]"))
            } else {
                Ok(())
            }
        }
    }
}

/// Wire form for an [`AuthMode`] — must match the
/// `#[serde(rename = "...")]` discriminators in `nexo-tool-meta`.
fn auth_mode_wire(mode: AuthMode) -> &'static str {
    match mode {
        AuthMode::ApiKey => "api_key",
        AuthMode::SetupToken => "setup_token",
        AuthMode::OAuthAuthCode => "oauth_auth_code",
        AuthMode::OAuthDeviceCode => "oauth_device_code",
        AuthMode::OAuthBundleImport => "oauth_bundle_import",
    }
}

/// Build an [`AdminRpcError::InvalidParams`] carrying a typed
/// [`LlmProviderError`] in `data` so the SPA can discriminate by
/// `code` without parsing free-form strings.
fn err_typed(err: LlmProviderError) -> AdminRpcResult {
    let data = serde_json::to_value(&err).unwrap_or(Value::Null);
    let msg = match &err {
        LlmProviderError::MissingField { field } => format!("missing required field `{field}`"),
        LlmProviderError::UnknownField { field } => format!("unknown field `{field}`"),
        LlmProviderError::InvalidFormat { field, hint } => {
            format!("invalid format for `{field}`: {hint}")
        }
        LlmProviderError::InvalidAuthMode { factory, mode } => {
            format!("auth_mode `{mode}` not supported by factory `{factory}`")
        }
        LlmProviderError::SessionExpired => "OAuth session expired".into(),
        LlmProviderError::SessionNotFound => "OAuth session not found".into(),
        LlmProviderError::OAuthExchangeFailed {
            upstream_status,
            message,
        } => format!("OAuth exchange failed (HTTP {upstream_status}): {message}"),
        LlmProviderError::ProbeFailed {
            upstream_status,
            message,
        } => format!("probe failed (HTTP {upstream_status}): {message}"),
        LlmProviderError::YamlWriteFailed { detail } => format!("yaml write failed: {detail}"),
        LlmProviderError::SecretWriteFailed { detail } => format!("secret write failed: {detail}"),
    };
    AdminRpcResult::err(AdminRpcError::InvalidParamsWithData { msg, data })
}

/// `nexo/admin/llm_providers/delete` — remove a provider block.
/// Reject when any agent in `agents.yaml` still references this
/// provider (caller must `agents/upsert` to swap providers first).
pub fn delete(
    llm: &dyn LlmYamlPatcher,
    agents: &dyn YamlPatcher,
    params: Value,
    reload_signal: &dyn Fn(),
) -> AdminRpcResult {
    let p: LlmProvidersDeleteParams = match serde_json::from_value(params) {
        Ok(p) => p,
        Err(e) => return AdminRpcResult::err(AdminRpcError::InvalidParams(e.to_string())),
    };
    let tenant_id = p
        .tenant_id
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string);

    // Refuse when any agent of the SAME scope uses this
    // provider. Cross-scope agents are unaffected — a global
    // delete doesn't break tenant-scoped agents pointing at a
    // tenant-scoped provider with the same id, and vice versa.
    let agent_ids = match agents.list_agent_ids() {
        Ok(ids) => ids,
        Err(e) => {
            return AdminRpcResult::err(AdminRpcError::Internal(format!("agents.yaml read: {e}")));
        }
    };
    for aid in &agent_ids {
        let Some(Value::String(provider)) = agents
            .read_agent_field(aid, "model.provider")
            .ok()
            .flatten()
        else {
            continue;
        };
        if provider != p.provider_id {
            continue;
        }
        // Match agent's tenant_id against the delete scope.
        let agent_tenant = agents
            .read_agent_field(aid, "tenant_id")
            .ok()
            .flatten()
            .and_then(|v| match v {
                Value::String(s) => Some(s),
                _ => None,
            });
        if agent_tenant.as_deref() == tenant_id.as_deref() {
            return AdminRpcResult::err(AdminRpcError::InvalidParams(format!(
                "provider `{}` still in use by agent `{aid}` (scope: {}); \
                 swap providers via agents/upsert before deleting",
                p.provider_id,
                tenant_id.as_deref().unwrap_or("global"),
            )));
        }
    }

    // Split the delete path mirroring
    // upsert. Tenant scope checks the tenant's provider list +
    // calls `remove_tenant_provider`; global scope keeps the
    // legacy path.
    let existed = match tenant_id.as_deref() {
        Some(tid) => matches!(
            llm.list_tenant_provider_ids(tid),
            Ok(ids) if ids.iter().any(|id| id == &p.provider_id)
        ),
        None => matches!(
            llm.list_provider_ids(),
            Ok(ids) if ids.iter().any(|id| id == &p.provider_id)
        ),
    };
    if !existed {
        return AdminRpcResult::ok(
            serde_json::to_value(LlmProvidersDeleteResponse { removed: false })
                .unwrap_or(Value::Null),
        );
    }
    let removed = match tenant_id.as_deref() {
        Some(tid) => llm.remove_tenant_provider(tid, &p.provider_id),
        None => llm.remove_provider(&p.provider_id),
    };
    match removed {
        Ok(()) => {
            reload_signal();
            AdminRpcResult::ok(
                serde_json::to_value(LlmProvidersDeleteResponse { removed: true })
                    .unwrap_or(Value::Null),
            )
        }
        Err(e) => AdminRpcResult::err(AdminRpcError::Internal(format!("yaml remove: {e}"))),
    }
}

/// Daemon-side probe surface.
///
/// Production adapter (`nexo_setup::llm_provider_probe::HttpLlmProviderProbe`)
/// reads the daemon's resolved `llm.yaml` config + env var,
/// hits `GET {base_url}/models` with bearer auth, and returns
/// a sanitised result. Mock impls in tests capture invocations
/// without touching the network.
#[async_trait]
pub trait LlmProvidersProbe: Send + Sync {
    /// Probe a configured provider end-to-end. Returns
    /// `Ok(_)` for every reachable outcome (including 4xx /
    /// 5xx with `ok: false`); returns `Err(_)` only for
    /// pre-flight problems (unknown provider, env var unset)
    /// so the wizard surfaces actionable signals.
    async fn probe(
        &self,
        provider_id: &str,
        tenant_id: Option<&str>,
    ) -> Result<LlmProviderProbeResponse, AdminRpcError>;

    /// Probe a DRAFT payload that hasn't landed in
    /// `llm.yaml` yet. Used by the SPA wizard to validate
    /// credentials BEFORE persistence so a bad key never lands on
    /// disk.
    ///
    /// Default impl returns `Internal "probe_draft not implemented"`
    /// so adapters that haven't migrated keep the legacy probe
    /// path working.
    async fn probe_draft(
        &self,
        _draft: LlmProviderProbeDraftInput,
    ) -> Result<LlmProviderProbeResponse, AdminRpcError> {
        Err(AdminRpcError::Internal(
            "probe_draft not implemented for this LlmProvidersProbe adapter".into(),
        ))
    }
}

/// Dispatcher entry point for `nexo/admin/llm_providers/probe`.
/// Validates the input, then forwards to the configured probe
/// impl. The handler does NOT touch `llm.yaml` itself; the
/// adapter wraps the existing [`LlmYamlPatcher`] for that.
pub async fn probe(probe_impl: &dyn LlmProvidersProbe, raw_params: Value) -> AdminRpcResult {
    match try_probe(probe_impl, raw_params).await {
        Ok(v) => AdminRpcResult::ok(v),
        Err(e) => AdminRpcResult::err(e),
    }
}

async fn try_probe(
    probe_impl: &dyn LlmProvidersProbe,
    raw_params: Value,
) -> Result<Value, AdminRpcError> {
    let input: LlmProviderProbeInput = serde_json::from_value(raw_params)
        .map_err(|e| AdminRpcError::InvalidParams(e.to_string()))?;
    if input.provider_id.is_empty() {
        return Err(AdminRpcError::InvalidParams(
            "provider_id cannot be empty".into(),
        ));
    }
    let response = probe_impl
        .probe(&input.provider_id, input.tenant_id.as_deref())
        .await?;
    serde_json::to_value(response).map_err(|e| AdminRpcError::Internal(e.to_string()))
}

/// `nexo/admin/llm_providers/probe_draft` handler.
///
/// Forwards a not-yet-persisted credential payload to the probe
/// adapter. Validates the input shape, then defers entirely to
/// `probe_impl.probe_draft(draft).await`. Errors return the same
/// `AdminRpcError` taxonomy as the regular probe — including the
/// `Internal "not implemented"` fallback for adapters that haven't
/// migrated.
pub async fn probe_draft(probe_impl: &dyn LlmProvidersProbe, raw_params: Value) -> AdminRpcResult {
    match try_probe_draft(probe_impl, raw_params).await {
        Ok(v) => AdminRpcResult::ok(v),
        Err(e) => AdminRpcResult::err(e),
    }
}

async fn try_probe_draft(
    probe_impl: &dyn LlmProvidersProbe,
    raw_params: Value,
) -> Result<Value, AdminRpcError> {
    let draft: LlmProviderProbeDraftInput = serde_json::from_value(raw_params)
        .map_err(|e| AdminRpcError::InvalidParams(e.to_string()))?;
    if draft.factory_type.trim().is_empty() {
        return Err(AdminRpcError::InvalidParams(
            "factory_type cannot be empty".into(),
        ));
    }
    if draft.base_url.trim().is_empty() {
        return Err(AdminRpcError::InvalidParams(
            "base_url cannot be empty".into(),
        ));
    }
    let response = probe_impl.probe_draft(draft).await?;
    serde_json::to_value(response).map_err(|e| AdminRpcError::Internal(e.to_string()))
}

// ──────────────────────────────────────────────────────────────────
// OAuth start/finish handlers.
//
// Two-step flow that suspends PKCE state in `VerifierStore` so the
// SPA never sees the verifier. Single-use sessions: `oauth_finish`
// removes the entry before exchanging the code, so a replay returns
// `SESSION_NOT_FOUND` even if the first call failed mid-exchange.
// TTL 10 min — operators reasonably finish a browser approval in
// under that.
// ──────────────────────────────────────────────────────────────────

const OAUTH_SESSION_TTL_SECS: i64 = 600;

/// `nexo/admin/llm_providers/oauth_start` — generate PKCE, persist
/// the verifier in the store, return `session_id + authorize_url`
/// (auth-code) or `session_id + user_code + verification_uri`
/// (device-code).
pub async fn oauth_start(
    verifier_store: &dyn nexo_llm_auth::VerifierStore,
    raw_params: Value,
) -> AdminRpcResult {
    let input: OAuthStartInput = match serde_json::from_value(raw_params) {
        Ok(v) => v,
        Err(e) => return AdminRpcResult::err(AdminRpcError::InvalidParams(e.to_string())),
    };
    if input.factory_type.trim().is_empty() {
        return AdminRpcResult::err(AdminRpcError::InvalidParams("factory_type is empty".into()));
    }

    match (input.factory_type.as_str(), input.auth_mode) {
        ("anthropic", AuthMode::OAuthAuthCode) => {
            oauth_start_anthropic(verifier_store, input).await
        }
        ("minimax", AuthMode::OAuthDeviceCode) => oauth_start_minimax(verifier_store, input).await,
        (factory, mode) => err_typed(LlmProviderError::InvalidAuthMode {
            factory: factory.to_string(),
            mode: auth_mode_wire(mode).to_string(),
        }),
    }
}

async fn oauth_start_anthropic(
    verifier_store: &dyn nexo_llm_auth::VerifierStore,
    input: OAuthStartInput,
) -> AdminRpcResult {
    let pkce = nexo_llm_auth::pkce::gen_pkce(nexo_llm_auth::pkce::StateEncoding::HexOnly);
    let authorize_url = nexo_llm_auth::anthropic::build_authorize_url(&pkce);
    let now = unix_now();
    let entry = nexo_llm_auth::VerifierEntry {
        pkce,
        factory_type: "anthropic".to_string(),
        flow_kind: "auth_code".to_string(),
        device_code: None,
        tenant_id: input.tenant_id,
        expires_at_unix: now + OAUTH_SESSION_TTL_SECS,
        created_at_unix: now,
    };
    let session_id = verifier_store.put(entry).await;
    let resp = OAuthStartResponse {
        session_id,
        authorize_url,
        expires_at_ms: (now + OAUTH_SESSION_TTL_SECS) * 1000,
        flow_kind: "auth_code".to_string(),
        user_code: None,
        polling_interval_ms: None,
    };
    AdminRpcResult::ok(serde_json::to_value(resp).unwrap_or(Value::Null))
}

async fn oauth_start_minimax(
    verifier_store: &dyn nexo_llm_auth::VerifierStore,
    input: OAuthStartInput,
) -> AdminRpcResult {
    let pkce = nexo_llm_auth::pkce::gen_pkce(nexo_llm_auth::pkce::StateEncoding::Base64Url);
    let region = nexo_llm_auth::minimax::Region::Global;
    let device = match nexo_llm_auth::minimax::request_user_code(region, &pkce, None).await {
        Ok(d) => d,
        Err(e) => {
            return err_typed(LlmProviderError::OAuthExchangeFailed {
                upstream_status: 0,
                message: format!("request_user_code: {e}"),
            });
        }
    };
    let now = unix_now();
    let entry = nexo_llm_auth::VerifierEntry {
        pkce,
        factory_type: "minimax".to_string(),
        flow_kind: "device_code".to_string(),
        device_code: Some(nexo_llm_auth::DeviceCodeContext {
            user_code: device.user_code.clone(),
            verification_uri: device.verification_uri.clone(),
            deadline_unix: device.deadline_unix,
            interval: device.interval,
        }),
        tenant_id: input.tenant_id,
        expires_at_unix: device.deadline_unix.min(now + OAUTH_SESSION_TTL_SECS),
        created_at_unix: now,
    };
    let session_id = verifier_store.put(entry).await;
    let resp = OAuthStartResponse {
        session_id,
        authorize_url: device.verification_uri,
        expires_at_ms: device.deadline_unix * 1000,
        flow_kind: "device_code".to_string(),
        user_code: Some(device.user_code),
        polling_interval_ms: Some(device.interval.as_millis() as u64),
    };
    AdminRpcResult::ok(serde_json::to_value(resp).unwrap_or(Value::Null))
}

/// `nexo/admin/llm_providers/oauth_finish` — exchange the code (or
/// poll the device-code endpoint) for an OAuth bundle, persist it
/// to the SecretsStore, patch yaml, and trigger reload. Single-
/// use session: the verifier entry is taken (removed) BEFORE the
/// exchange, so a failed exchange surfaces `SESSION_NOT_FOUND` on
/// retry — the operator must restart with a fresh `oauth_start`.
pub async fn oauth_finish(
    verifier_store: &dyn nexo_llm_auth::VerifierStore,
    secrets: &dyn SecretsStore,
    patcher: &dyn LlmYamlPatcher,
    raw_params: Value,
    reload_signal: &(dyn Fn() + Send + Sync),
) -> AdminRpcResult {
    let input: OAuthFinishInput = match serde_json::from_value(raw_params) {
        Ok(v) => v,
        Err(e) => return AdminRpcResult::err(AdminRpcError::InvalidParams(e.to_string())),
    };
    if input.session_id.trim().is_empty() {
        return AdminRpcResult::err(AdminRpcError::InvalidParams("session_id is empty".into()));
    }
    if input.instance_id.trim().is_empty() {
        return AdminRpcResult::err(AdminRpcError::InvalidParams("instance_id is empty".into()));
    }

    // Single-use: peek_status discriminates expired vs missing
    // for diagnostic-quality error codes; take() removes it.
    use nexo_llm_auth::SessionStatus;
    match verifier_store.peek_status(&input.session_id).await {
        SessionStatus::Live => {}
        SessionStatus::Expired => {
            // Burn the entry so it doesn't linger.
            let _ = verifier_store.take(&input.session_id).await;
            return err_typed(LlmProviderError::SessionExpired);
        }
        SessionStatus::Missing => {
            return err_typed(LlmProviderError::SessionNotFound);
        }
    }
    let entry = match verifier_store.take(&input.session_id).await {
        Some(e) => e,
        None => return err_typed(LlmProviderError::SessionNotFound),
    };

    let bundle = match (entry.factory_type.as_str(), entry.flow_kind.as_str()) {
        ("anthropic", "auth_code") => {
            let code_payload = match input.code.as_deref() {
                Some(c) if !c.trim().is_empty() => c,
                _ => {
                    return AdminRpcResult::err(AdminRpcError::InvalidParams(
                        "auth_code flow requires `code` payload".into(),
                    ));
                }
            };
            let (code, state) = match nexo_llm_auth::pkce::parse_code_payload(code_payload) {
                Ok(t) => t,
                Err(e) => {
                    return err_typed(LlmProviderError::OAuthExchangeFailed {
                        upstream_status: 0,
                        message: format!("parse code: {e}"),
                    });
                }
            };
            match nexo_llm_auth::anthropic::exchange_code(
                &entry.pkce,
                &code,
                &state,
                nexo_llm_auth::anthropic::TOKEN_URL,
            )
            .await
            {
                Ok(b) => b,
                Err(e) => {
                    return err_typed(LlmProviderError::OAuthExchangeFailed {
                        upstream_status: 0,
                        message: e.to_string(),
                    });
                }
            }
        }
        ("minimax", "device_code") => {
            let device_ctx = match entry.device_code.as_ref() {
                Some(d) => d,
                None => {
                    return AdminRpcResult::err(AdminRpcError::Internal(
                        "device_code session missing device_code context".into(),
                    ));
                }
            };
            let device = nexo_llm_auth::minimax::DeviceCodeResponse {
                user_code: device_ctx.user_code.clone(),
                verification_uri: device_ctx.verification_uri.clone(),
                deadline_unix: device_ctx.deadline_unix,
                interval: device_ctx.interval,
            };
            match nexo_llm_auth::minimax::poll_token(
                nexo_llm_auth::minimax::Region::Global,
                &entry.pkce,
                &device,
                None,
            )
            .await
            {
                Ok(b) => b,
                Err(e) => {
                    return err_typed(LlmProviderError::OAuthExchangeFailed {
                        upstream_status: 0,
                        message: e.to_string(),
                    });
                }
            }
        }
        (factory, kind) => {
            return AdminRpcResult::err(AdminRpcError::Internal(format!(
                "unsupported (factory={factory}, flow_kind={kind})"
            )));
        }
    };

    // Persist bundle JSON to the SecretsStore. Derived id
    // mirrors the Anthropic CLI convention so the runtime
    // `OAuthState::load(path)` can read it back.
    let bundle_json = match bundle.to_json_pretty() {
        Ok(s) => s,
        Err(e) => {
            return err_typed(LlmProviderError::SecretWriteFailed {
                detail: format!("serialise bundle: {e}"),
            });
        }
    };
    let secret_id = oauth_bundle_secret_id(&input.instance_id);
    let bundle_path = match secrets.write(&secret_id, &bundle_json).await {
        Ok(r) => r.path,
        Err(e) => {
            return err_typed(LlmProviderError::SecretWriteFailed {
                detail: e.to_string(),
            });
        }
    };

    // Patch yaml: auth.mode = oauth_bundle, auth.bundle = path.
    let tenant_id = entry.tenant_id.clone();
    let write_field = |dotted: &str, value: Value| -> anyhow::Result<()> {
        match tenant_id.as_deref() {
            Some(tid) => {
                patcher.upsert_tenant_provider_field(tid, &input.instance_id, dotted, value)
            }
            None => patcher.upsert_provider_field(&input.instance_id, dotted, value),
        }
    };
    if let Err(e) = write_field("auth.mode", Value::String("oauth_bundle".into())) {
        return err_typed(LlmProviderError::YamlWriteFailed {
            detail: e.to_string(),
        });
    }
    if let Err(e) = write_field(
        "auth.bundle",
        Value::String(bundle_path.display().to_string()),
    ) {
        return err_typed(LlmProviderError::YamlWriteFailed {
            detail: e.to_string(),
        });
    }
    reload_signal();

    let resp = OAuthFinishResponse {
        ok: true,
        account_email: bundle.account_email.clone(),
        expires_at_ms: bundle.expires_at * 1000,
        secret_id,
    };
    AdminRpcResult::ok(serde_json::to_value(resp).unwrap_or(Value::Null))
}

/// Derive a SecretsStore name for an OAuth bundle from the
/// instance id. Mirrors `secret_id_for_field` shape: prefix
/// `LLM_`, uppercase, non-alnum → `_`, suffix `_OAUTH_BUNDLE`.
fn oauth_bundle_secret_id(instance_id: &str) -> String {
    let mut out = secret_id_for_instance(instance_id);
    out.push_str("_OAUTH_BUNDLE");
    out
}

fn unix_now() -> i64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs() as i64
}

fn read_summary(
    patcher: &dyn LlmYamlPatcher,
    provider_id: &str,
) -> anyhow::Result<Option<LlmProviderSummary>> {
    let base_url = match patcher.read_provider_field(provider_id, "base_url")? {
        Some(Value::String(s)) => s,
        _ => return Ok(None),
    };
    let api_key_env = match patcher.read_provider_field(provider_id, "api_key_env")? {
        Some(Value::String(s)) => s,
        _ => String::new(),
    };
    Ok(Some(LlmProviderSummary {
        id: provider_id.to_string(),
        base_url,
        api_key_env,
        // Global-scope reads stamp `None`.
        // Tenant-scoped reads (when the handler honours
        // `tenant_id` filter) populate this field with the
        // owning tenant id. Wire-up of the tenant read path
        // lands as a follow-up; today the reader is global
        // only so emitting None here is correct.
        tenant_scope: None,
    }))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::sync::Mutex;

    #[derive(Default)]
    struct MockLlm {
        providers: Mutex<HashMap<String, HashMap<String, Value>>>,
        /// Tenant providers keyed by
        /// `(tenant_id, provider_id)`.
        tenant_providers: Mutex<HashMap<(String, String), HashMap<String, Value>>>,
    }
    impl MockLlm {
        fn with(provs: &[(&str, &str, &str)]) -> Self {
            let me = Self::default();
            for (id, base_url, env) in provs {
                me.providers
                    .lock()
                    .unwrap()
                    .entry(id.to_string())
                    .or_default()
                    .insert("base_url".into(), Value::String((*base_url).into()));
                me.providers
                    .lock()
                    .unwrap()
                    .entry(id.to_string())
                    .or_default()
                    .insert("api_key_env".into(), Value::String((*env).into()));
            }
            me
        }
    }
    impl LlmYamlPatcher for MockLlm {
        fn list_provider_ids(&self) -> anyhow::Result<Vec<String>> {
            let mut v: Vec<String> = self.providers.lock().unwrap().keys().cloned().collect();
            v.sort();
            Ok(v)
        }
        fn read_provider_field(&self, id: &str, dotted: &str) -> anyhow::Result<Option<Value>> {
            Ok(self
                .providers
                .lock()
                .unwrap()
                .get(id)
                .and_then(|m| m.get(dotted).cloned()))
        }
        fn upsert_provider_field(
            &self,
            id: &str,
            dotted: &str,
            value: Value,
        ) -> anyhow::Result<()> {
            self.providers
                .lock()
                .unwrap()
                .entry(id.to_string())
                .or_default()
                .insert(dotted.to_string(), value);
            Ok(())
        }
        fn remove_provider(&self, id: &str) -> anyhow::Result<()> {
            self.providers.lock().unwrap().remove(id);
            Ok(())
        }
        fn list_tenant_provider_ids(&self, tenant_id: &str) -> anyhow::Result<Vec<String>> {
            let mut v: Vec<String> = self
                .tenant_providers
                .lock()
                .unwrap()
                .keys()
                .filter(|(t, _)| t == tenant_id)
                .map(|(_, p)| p.clone())
                .collect();
            v.sort();
            Ok(v)
        }
        fn read_tenant_provider_field(
            &self,
            tenant_id: &str,
            provider_id: &str,
            dotted: &str,
        ) -> anyhow::Result<Option<Value>> {
            Ok(self
                .tenant_providers
                .lock()
                .unwrap()
                .get(&(tenant_id.to_string(), provider_id.to_string()))
                .and_then(|m| m.get(dotted).cloned()))
        }
        fn upsert_tenant_provider_field(
            &self,
            tenant_id: &str,
            provider_id: &str,
            dotted: &str,
            value: Value,
        ) -> anyhow::Result<()> {
            self.tenant_providers
                .lock()
                .unwrap()
                .entry((tenant_id.to_string(), provider_id.to_string()))
                .or_default()
                .insert(dotted.to_string(), value);
            Ok(())
        }
        fn remove_tenant_provider(&self, tenant_id: &str, provider_id: &str) -> anyhow::Result<()> {
            self.tenant_providers
                .lock()
                .unwrap()
                .remove(&(tenant_id.to_string(), provider_id.to_string()));
            Ok(())
        }
    }

    #[derive(Default)]
    struct MockAgents {
        agents: Mutex<HashMap<String, HashMap<String, Value>>>,
    }
    impl MockAgents {
        fn with_provider(provider: &str) -> Self {
            let me = Self::default();
            me.agents
                .lock()
                .unwrap()
                .entry("ana".into())
                .or_default()
                .insert("model.provider".into(), Value::String(provider.into()));
            me
        }
    }
    impl YamlPatcher for MockAgents {
        fn list_agent_ids(&self) -> anyhow::Result<Vec<String>> {
            Ok(self.agents.lock().unwrap().keys().cloned().collect())
        }
        fn read_agent_field(&self, id: &str, dotted: &str) -> anyhow::Result<Option<Value>> {
            Ok(self
                .agents
                .lock()
                .unwrap()
                .get(id)
                .and_then(|m| m.get(dotted).cloned()))
        }
        fn upsert_agent_field(
            &self,
            _id: &str,
            _dotted: &str,
            _value: Value,
        ) -> anyhow::Result<()> {
            Ok(())
        }
        fn remove_agent(&self, _id: &str) -> anyhow::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn llm_providers_list_returns_alpha_order() {
        let llm = MockLlm::with(&[
            ("zphi", "u1", "K1"),
            ("anthropic", "u2", "K2"),
            ("minimax", "u3", "K3"),
        ]);
        let result = list(&llm);
        let response: LlmProvidersListResponse =
            serde_json::from_value(result.result.unwrap()).unwrap();
        assert_eq!(response.providers.len(), 3);
        assert_eq!(response.providers[0].id, "anthropic");
        assert_eq!(response.providers[1].id, "minimax");
        assert_eq!(response.providers[2].id, "zphi");
    }

    #[tokio::test]
    async fn llm_providers_upsert_validates_env_var_exists() {
        let llm = MockLlm::default();
        // Use an env var guaranteed not present.
        let result = upsert(
            &llm,
            None,
            None,
            serde_json::json!({
                "id": "newp",
                "base_url": "https://x",
                "api_key_env": "NEXO_DEFINITELY_NOT_SET_VAR_42"
            }),
            &|| {},
        )
        .await;
        let err = result.error.expect("error");
        assert!(matches!(err, AdminRpcError::InvalidParams(_)));
    }

    #[tokio::test]
    async fn llm_providers_upsert_writes_when_env_var_present() {
        let llm = MockLlm::default();
        // PATH is always set.
        let result = upsert(
            &llm,
            None,
            None,
            serde_json::json!({
                "id": "newp",
                "base_url": "https://x",
                "api_key_env": "PATH"
            }),
            &|| {},
        )
        .await;
        assert!(result.result.is_some());
        // Stored.
        assert_eq!(llm.list_provider_ids().unwrap(), vec!["newp".to_string()]);
    }

    #[test]
    fn llm_providers_delete_rejects_when_agent_uses_provider() {
        let llm = MockLlm::with(&[("minimax", "u", "K")]);
        let agents = MockAgents::with_provider("minimax");
        let result = delete(
            &llm,
            &agents,
            serde_json::json!({ "provider_id": "minimax" }),
            &|| {},
        );
        let err = result.error.expect("error");
        assert!(matches!(err, AdminRpcError::InvalidParams(_)));
        // Provider still present.
        assert!(llm.list_provider_ids().unwrap().contains(&"minimax".into()));
    }

    #[test]
    fn llm_providers_delete_removes_unused_provider() {
        let llm = MockLlm::with(&[("retired", "u", "K")]);
        let agents = MockAgents::with_provider("minimax"); // not retired
        let result = delete(
            &llm,
            &agents,
            serde_json::json!({ "provider_id": "retired" }),
            &|| {},
        );
        let response: LlmProvidersDeleteResponse =
            serde_json::from_value(result.result.unwrap()).unwrap();
        assert!(response.removed);
        assert!(llm.list_provider_ids().unwrap().is_empty());
    }

    #[test]
    fn llm_providers_delete_unknown_id_idempotent() {
        let llm = MockLlm::default();
        let agents = MockAgents::default();
        let result = delete(
            &llm,
            &agents,
            serde_json::json!({ "provider_id": "ghost" }),
            &|| {},
        );
        let response: LlmProvidersDeleteResponse =
            serde_json::from_value(result.result.unwrap()).unwrap();
        assert!(!response.removed);
    }

    // ── tenant-scoped CRUD ──

    /// `tenant_id: Some` upsert writes under tenant namespace
    /// + leaves the global table untouched. Resulting summary
    /// echoes `tenant_scope`.
    #[tokio::test]
    async fn llm_providers_upsert_with_tenant_id_writes_under_tenant_namespace() {
        // Make sure the env var the handler validates exists.
        std::env::set_var("MINIMAX_KEY_ACME_TEST", "value");
        let llm = MockLlm::default();
        let result = upsert(
            &llm,
            None,
            None,
            serde_json::json!({
                "id": "minimax",
                "base_url": "https://api.minimax.io",
                "api_key_env": "MINIMAX_KEY_ACME_TEST",
                "tenant_id": "acme",
            }),
            &|| {},
        )
        .await;
        assert!(result.error.is_none(), "{result:?}");
        let summary: LlmProviderSummary = serde_json::from_value(result.result.unwrap()).unwrap();
        assert_eq!(summary.tenant_scope.as_deref(), Some("acme"));
        // Global table untouched.
        assert!(llm.list_provider_ids().unwrap().is_empty());
        // Tenant namespace populated.
        assert_eq!(
            llm.list_tenant_provider_ids("acme").unwrap(),
            vec!["minimax".to_string()]
        );
        let v = llm
            .read_tenant_provider_field("acme", "minimax", "base_url")
            .unwrap();
        assert_eq!(v, Some(Value::String("https://api.minimax.io".into())));
    }

    /// Tenant delete removes ONLY the tenant-scoped block. A
    /// global provider with the same id stays intact (the two
    /// scopes are independent).
    #[tokio::test]
    async fn llm_providers_delete_with_tenant_id_isolates_from_global() {
        std::env::set_var("MINIMAX_KEY", "v");
        // Seed both: a global "minimax" + a tenant "acme.minimax".
        let llm = MockLlm::with(&[("minimax", "https://global", "MINIMAX_KEY")]);
        llm.upsert_tenant_provider_field(
            "acme",
            "minimax",
            "base_url",
            Value::String("https://acme".into()),
        )
        .unwrap();
        let agents = MockAgents::default(); // no agents reference these
        let result = delete(
            &llm,
            &agents,
            serde_json::json!({ "provider_id": "minimax", "tenant_id": "acme" }),
            &|| {},
        );
        let response: LlmProvidersDeleteResponse =
            serde_json::from_value(result.result.unwrap()).unwrap();
        assert!(response.removed);
        // Global still there.
        assert!(llm.list_provider_ids().unwrap().contains(&"minimax".into()));
        // Tenant scope cleared.
        assert!(llm.list_tenant_provider_ids("acme").unwrap().is_empty());
    }

    /// Tenant delete refuses when an agent OF THE SAME tenant
    /// scope still uses the provider.
    #[tokio::test]
    async fn llm_providers_delete_tenant_rejects_when_same_scope_agent_uses_it() {
        let llm = MockLlm::default();
        llm.upsert_tenant_provider_field(
            "acme",
            "minimax",
            "base_url",
            Value::String("https://acme".into()),
        )
        .unwrap();
        let agents = MockAgents::default();
        // Seed an agent in tenant `acme` using minimax.
        agents
            .agents
            .lock()
            .unwrap()
            .entry("ana".into())
            .or_default()
            .insert("model.provider".into(), Value::String("minimax".into()));
        agents
            .agents
            .lock()
            .unwrap()
            .entry("ana".into())
            .or_default()
            .insert("tenant_id".into(), Value::String("acme".into()));
        let result = delete(
            &llm,
            &agents,
            serde_json::json!({ "provider_id": "minimax", "tenant_id": "acme" }),
            &|| {},
        );
        let err = result.error.expect("error");
        assert!(matches!(err, AdminRpcError::InvalidParams(_)));
        // Tenant block still present.
        assert_eq!(
            llm.list_tenant_provider_ids("acme").unwrap(),
            vec!["minimax".to_string()]
        );
    }

    /// Cross-scope delete: a global delete does NOT block on
    /// tenant-scoped agents using a same-named tenant
    /// provider. Tenant agent still has its own provider; the
    /// global delete is allowed.
    #[tokio::test]
    async fn llm_providers_delete_global_unaffected_by_tenant_agent_using_same_id() {
        let llm = MockLlm::with(&[("minimax", "u", "K")]);
        llm.upsert_tenant_provider_field(
            "acme",
            "minimax",
            "base_url",
            Value::String("https://acme".into()),
        )
        .unwrap();
        let agents = MockAgents::default();
        // Tenant `acme` agent uses minimax — but the delete
        // targets the GLOBAL minimax, not acme's.
        agents
            .agents
            .lock()
            .unwrap()
            .entry("ana".into())
            .or_default()
            .insert("model.provider".into(), Value::String("minimax".into()));
        agents
            .agents
            .lock()
            .unwrap()
            .entry("ana".into())
            .or_default()
            .insert("tenant_id".into(), Value::String("acme".into()));
        let result = delete(
            &llm,
            &agents,
            // No tenant_id → global scope.
            serde_json::json!({ "provider_id": "minimax" }),
            &|| {},
        );
        let response: LlmProvidersDeleteResponse =
            serde_json::from_value(result.result.unwrap()).unwrap();
        assert!(response.removed);
        // Global minimax gone, tenant minimax intact.
        assert!(llm.list_provider_ids().unwrap().is_empty());
        assert_eq!(
            llm.list_tenant_provider_ids("acme").unwrap(),
            vec!["minimax".to_string()]
        );
    }

    // ────────────────────────────────────────────────────────
    // Probe handler tests.
    // ────────────────────────────────────────────────────────

    /// Mock that captures invocations + returns a canned
    /// `LlmProviderProbeResponse` (or `Err`).
    struct MockProbe {
        result: std::sync::Mutex<Result<LlmProviderProbeResponse, AdminRpcError>>,
        calls: tokio::sync::Mutex<Vec<(String, Option<String>)>>,
    }

    impl MockProbe {
        fn ok(response: LlmProviderProbeResponse) -> Self {
            Self {
                result: std::sync::Mutex::new(Ok(response)),
                calls: tokio::sync::Mutex::new(Vec::new()),
            }
        }

        fn err(e: AdminRpcError) -> Self {
            Self {
                result: std::sync::Mutex::new(Err(e)),
                calls: tokio::sync::Mutex::new(Vec::new()),
            }
        }
    }

    #[async_trait]
    impl LlmProvidersProbe for MockProbe {
        async fn probe(
            &self,
            provider_id: &str,
            tenant_id: Option<&str>,
        ) -> Result<LlmProviderProbeResponse, AdminRpcError> {
            self.calls
                .lock()
                .await
                .push((provider_id.to_string(), tenant_id.map(String::from)));
            let mut guard = self.result.lock().unwrap();
            // Replace the stored Result with a fresh
            // placeholder so we can move out of it without
            // requiring `Clone` on AdminRpcError.
            let placeholder = Ok(LlmProviderProbeResponse::default());
            std::mem::replace(&mut *guard, placeholder)
        }
    }

    #[tokio::test]
    async fn probe_validates_empty_provider_id() {
        let mock = MockProbe::ok(LlmProviderProbeResponse::default());
        let result = probe(&mock, serde_json::json!({"provider_id": ""})).await;
        let err = result.error.expect("expected error");
        match err {
            AdminRpcError::InvalidParams(msg) => assert!(msg.contains("empty")),
            other => panic!("expected InvalidParams, got {other:?}"),
        }
        assert!(mock.calls.lock().await.is_empty());
    }

    #[tokio::test]
    async fn probe_propagates_store_error() {
        let mock = MockProbe::err(AdminRpcError::InvalidParams("env var FOO not set".into()));
        let result = probe(&mock, serde_json::json!({"provider_id": "minimax"})).await;
        let err = result.error.expect("expected error");
        match err {
            AdminRpcError::InvalidParams(msg) => assert!(msg.contains("env var")),
            other => panic!("expected InvalidParams, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn probe_returns_response_on_success() {
        let mock = MockProbe::ok(LlmProviderProbeResponse {
            ok: true,
            status: 200,
            latency_ms: 142,
            model_count: Some(5),
            model_names: None,
            error: None,
        });
        let result = probe(
            &mock,
            serde_json::json!({"provider_id": "minimax", "tenant_id": "acme"}),
        )
        .await;
        let value = result.result.expect("ok");
        assert_eq!(value["ok"], true);
        assert_eq!(value["status"], 200);
        assert_eq!(value["model_count"], 5);
        let calls = mock.calls.lock().await;
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].0, "minimax");
        assert_eq!(calls[0].1.as_deref(), Some("acme"));
    }

    // ── schema-driven upsert ────────────────────

    use nexo_tool_meta::admin::llm_providers::{
        AuthMode, CredentialFieldDescriptor, FieldKind, FieldValidation,
    };

    /// In-memory `FactorySchemaLookup` mock: holds one factory's
    /// schema + auth modes. Convenient for the schema-driven
    /// upsert tests below.
    struct MockSchema {
        factory_id: String,
        schema: Vec<CredentialFieldDescriptor>,
        modes: Vec<AuthMode>,
    }
    impl FactorySchemaLookup for MockSchema {
        fn credential_schema(&self, factory_id: &str) -> Option<Vec<CredentialFieldDescriptor>> {
            (factory_id == self.factory_id).then(|| self.schema.clone())
        }
        fn supported_auth_modes(&self, factory_id: &str) -> Option<Vec<AuthMode>> {
            (factory_id == self.factory_id).then(|| self.modes.clone())
        }
    }

    fn minimax_schema() -> MockSchema {
        MockSchema {
            factory_id: "minimax".into(),
            schema: vec![
                CredentialFieldDescriptor {
                    name: "api_key".into(),
                    label: "API key".into(),
                    kind: FieldKind::Password,
                    required: true,
                    secret: true,
                    default: None,
                    help: None,
                    validation: Some(FieldValidation::Length { min: 1, max: 200 }),
                    depends_on: None,
                },
                CredentialFieldDescriptor {
                    name: "group_id".into(),
                    label: "Group ID".into(),
                    kind: FieldKind::Text,
                    required: true,
                    secret: false,
                    default: None,
                    help: None,
                    validation: Some(FieldValidation::Regex {
                        pattern: "^[0-9]{10,20}$".into(),
                        hint: "10-20 digits".into(),
                    }),
                    depends_on: None,
                },
            ],
            modes: vec![AuthMode::ApiKey, AuthMode::OAuthDeviceCode],
        }
    }

    /// In-memory `SecretsStore` mock: records every write so the
    /// test can assert what landed where.
    struct MockSecrets {
        writes: Mutex<Vec<(String, String)>>,
    }
    #[async_trait]
    impl SecretsStore for MockSecrets {
        async fn write(
            &self,
            name: &str,
            value: &str,
        ) -> Result<nexo_tool_meta::admin::secrets::SecretsWriteResponse, AdminRpcError> {
            self.writes
                .lock()
                .unwrap()
                .push((name.to_string(), value.to_string()));
            Ok(nexo_tool_meta::admin::secrets::SecretsWriteResponse {
                path: std::path::PathBuf::from(format!("/mock/{name}.txt")),
                overwrote_env: false,
            })
        }
    }

    /// Happy path — full minimax payload validates, persists the
    /// secret api_key under a derived id, writes group_id inline,
    /// and reload_signal fires once.
    #[tokio::test]
    async fn schema_driven_upsert_persists_secret_and_yaml() {
        let llm = MockLlm::default();
        let secrets = MockSecrets {
            writes: Mutex::new(Vec::new()),
        };
        let schema = minimax_schema();
        let calls = std::sync::atomic::AtomicUsize::new(0);
        let result = upsert(
            &llm,
            Some(&secrets),
            Some(&schema),
            serde_json::json!({
                "id": "minimax-cliente-a",
                "factory_type": "minimax",
                "base_url": "https://api.minimax.io/v1",
                "auth_mode": "api_key",
                "fields": {
                    "api_key": "sk-test-key",
                    "group_id": "1234567890123",
                },
            }),
            &|| {
                calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            },
        )
        .await;
        assert!(result.error.is_none(), "{result:?}");
        assert_eq!(
            calls.load(std::sync::atomic::Ordering::Relaxed),
            1,
            "reload_signal must fire exactly once"
        );
        // Secret persisted under derived id with the field name suffix.
        let writes = secrets.writes.lock().unwrap().clone();
        assert_eq!(writes.len(), 1);
        assert_eq!(writes[0].0, "LLM_MINIMAX_CLIENTE_A_API_KEY");
        assert_eq!(writes[0].1, "sk-test-key");
        // Yaml has factory_type + group_id inline + api_key_secret_id ref.
        let providers = llm.providers.lock().unwrap();
        let entry = providers.get("minimax-cliente-a").unwrap();
        assert_eq!(
            entry.get("factory_type"),
            Some(&Value::String("minimax".into()))
        );
        assert_eq!(
            entry.get("group_id"),
            Some(&Value::String("1234567890123".into()))
        );
        assert_eq!(
            entry.get("api_key_secret_id"),
            Some(&Value::String("LLM_MINIMAX_CLIENTE_A_API_KEY".into()))
        );
    }

    /// Required field absent → MissingField error code, no
    /// side-effect on disk.
    #[tokio::test]
    async fn schema_driven_upsert_rejects_missing_required_field() {
        let llm = MockLlm::default();
        let secrets = MockSecrets {
            writes: Mutex::new(Vec::new()),
        };
        let schema = minimax_schema();
        let result = upsert(
            &llm,
            Some(&secrets),
            Some(&schema),
            serde_json::json!({
                "id": "minimax-cliente-b",
                "factory_type": "minimax",
                "base_url": "https://x",
                "fields": { "api_key": "sk-x" },  // group_id missing
            }),
            &|| {},
        )
        .await;
        let err = result.error.expect("MissingField error");
        let data = err.data().expect("typed data");
        assert_eq!(data["code"], "MISSING_FIELD");
        assert_eq!(data["field"], "group_id");
        // Nothing written.
        assert!(secrets.writes.lock().unwrap().is_empty());
        assert!(llm.list_provider_ids().unwrap().is_empty());
    }

    /// Field present but failing the regex validation → InvalidFormat.
    #[tokio::test]
    async fn schema_driven_upsert_rejects_invalid_format() {
        let llm = MockLlm::default();
        let secrets = MockSecrets {
            writes: Mutex::new(Vec::new()),
        };
        let schema = minimax_schema();
        let result = upsert(
            &llm,
            Some(&secrets),
            Some(&schema),
            serde_json::json!({
                "id": "minimax-cliente-c",
                "factory_type": "minimax",
                "base_url": "https://x",
                "fields": {
                    "api_key": "sk-x",
                    "group_id": "not-numeric",  // regex fails
                },
            }),
            &|| {},
        )
        .await;
        let err = result.error.expect("InvalidFormat error");
        let data = err.data().expect("typed data");
        assert_eq!(data["code"], "INVALID_FORMAT");
        assert_eq!(data["field"], "group_id");
        assert!(secrets.writes.lock().unwrap().is_empty());
    }

    /// Field outside the schema → UnknownField. Defensive against
    /// payload typos.
    #[tokio::test]
    async fn schema_driven_upsert_rejects_unknown_field() {
        let llm = MockLlm::default();
        let secrets = MockSecrets {
            writes: Mutex::new(Vec::new()),
        };
        let schema = minimax_schema();
        let result = upsert(
            &llm,
            Some(&secrets),
            Some(&schema),
            serde_json::json!({
                "id": "minimax-cliente-d",
                "factory_type": "minimax",
                "base_url": "https://x",
                "fields": {
                    "api_key": "sk-x",
                    "group_id": "1234567890",
                    "garbage": "what",
                },
            }),
            &|| {},
        )
        .await;
        let err = result.error.expect("UnknownField error");
        let data = err.data().expect("typed data");
        assert_eq!(data["code"], "UNKNOWN_FIELD");
    }

    /// Factory id absent from the lookup → InvalidAuthMode with
    /// `<unknown factory>`. Tests the case where the operator
    /// supplies a factory the daemon doesn't have registered.
    #[tokio::test]
    async fn schema_driven_upsert_rejects_unknown_factory() {
        let llm = MockLlm::default();
        let secrets = MockSecrets {
            writes: Mutex::new(Vec::new()),
        };
        let schema = minimax_schema();
        let result = upsert(
            &llm,
            Some(&secrets),
            Some(&schema),
            serde_json::json!({
                "id": "ghost-instance",
                "factory_type": "ghost",
                "base_url": "https://x",
                "fields": { "api_key": "sk-x" },
            }),
            &|| {},
        )
        .await;
        let err = result.error.expect("InvalidAuthMode error");
        let data = err.data().expect("typed data");
        assert_eq!(data["code"], "INVALID_AUTH_MODE");
    }

    /// Legacy path: empty `fields` → falls back to `api_key_env`
    /// branch, preserves pre-82.10.u behaviour for existing
    /// microapps.
    #[tokio::test]
    async fn schema_driven_upsert_falls_back_to_legacy_when_fields_empty() {
        let llm = MockLlm::default();
        // Schema absent — the legacy path doesn't need a lookup.
        let result = upsert(
            &llm,
            None,
            None,
            serde_json::json!({
                "id": "legacy-minimax",
                "base_url": "https://x",
                "api_key_env": "PATH",  // PATH always set
            }),
            &|| {},
        )
        .await;
        assert!(result.error.is_none(), "legacy path must still work");
    }
}