nika 0.35.4

Semantic YAML workflow engine for AI tasks - DAG execution, MCP integration, multi-provider LLM support
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
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
//! Rig-core provider wrapper
//!
//! Wraps rig-core providers (Anthropic, OpenAI) with a unified interface
//! that integrates with Nika's workflow system.
//!
//! ## Architecture
//!
//! This module provides two main components:
//!
//! 1. **RigProvider** - Enum wrapping Claude/OpenAI provider clients
//! 2. **NikaMcpTool** - Wrapper implementing rig-core's `ToolDyn` for MCP tools
//!
//! ## MCP Integration
//!
//! We use rig-core's `ToolDyn` trait to wrap our MCP tools, avoiding the rmcp
//! version conflict (rig-core uses rmcp 0.13, we use rmcp 0.16).
//!
//! ```text
//! NikaMcpToolDef (our definition)
//!//! NikaMcpTool (implements ToolDyn)
//!//! rig-core AgentBuilder.tool()
//! ```

use crate::mcp::McpClient;
use crate::util::STREAM_CHUNK_TIMEOUT;
use futures::StreamExt;

// Import InferenceBackend trait for native inference methods
#[cfg(feature = "native-inference")]
use crate::provider::native::InferenceBackend;
use rig::client::{CompletionClient, ProviderClient};
use rig::completion::{CompletionModel as _, GetTokenUsage, Prompt, PromptError, ToolDefinition};
use rig::providers::{anthropic, deepseek, gemini, groq, mistral, openai, xai};
use rig::streaming::StreamedAssistantContent;
use rig::tool::{ToolDyn, ToolError};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use tokio::sync::mpsc;
use tokio::time::timeout;

// ═══════════════════════════════════════════════════════════════════════════
// TOOL ERROR TYPES
// ═══════════════════════════════════════════════════════════════════════════

/// MCP tool call error with semantic error kinds
///
/// Provides proper error semantics instead of wrapping in std::io::Error.
#[derive(Debug)]
pub struct McpToolError {
    kind: McpToolErrorKind,
    message: String,
}

/// Error kinds for MCP tool calls
#[derive(Debug, Clone, Copy)]
pub enum McpToolErrorKind {
    /// Invalid JSON arguments
    InvalidArguments,
    /// MCP client not configured
    NotConfigured,
    /// MCP tool call failed
    CallFailed,
    /// Failed to serialize/deserialize result
    SerializationError,
}

impl McpToolError {
    /// Create an invalid arguments error
    pub fn invalid_args(msg: impl Into<String>) -> Self {
        Self {
            kind: McpToolErrorKind::InvalidArguments,
            message: msg.into(),
        }
    }

    /// Create a not configured error
    pub fn not_configured(msg: impl Into<String>) -> Self {
        Self {
            kind: McpToolErrorKind::NotConfigured,
            message: msg.into(),
        }
    }

    /// Create a call failed error
    pub fn call_failed(msg: impl Into<String>) -> Self {
        Self {
            kind: McpToolErrorKind::CallFailed,
            message: msg.into(),
        }
    }

    /// Create a serialization error
    pub fn serialization(msg: impl Into<String>) -> Self {
        Self {
            kind: McpToolErrorKind::SerializationError,
            message: msg.into(),
        }
    }
}

impl std::fmt::Display for McpToolError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let kind_str = match self.kind {
            McpToolErrorKind::InvalidArguments => "InvalidArguments",
            McpToolErrorKind::NotConfigured => "NotConfigured",
            McpToolErrorKind::CallFailed => "CallFailed",
            McpToolErrorKind::SerializationError => "SerializationError",
        };
        write!(f, "[{}] {}", kind_str, self.message)
    }
}

impl std::error::Error for McpToolError {}

/// Options for LLM inference
///
/// Provides fine-grained control over inference behavior.
#[derive(Debug, Clone, Default)]
pub struct InferOptions {
    /// Model identifier (uses provider default if None)
    pub model: Option<String>,
    /// Temperature for sampling (0.0-2.0, lower = more deterministic)
    pub temperature: Option<f64>,
    /// Maximum tokens to generate
    pub max_tokens: Option<u32>,
    /// System prompt to prepend
    pub system: Option<String>,
}

/// Provider type enum for rig-core providers
///
/// Nika leverages rig-core's native multi-provider support.
/// Each variant wraps the corresponding rig-core client.
#[derive(Debug, Clone)]
pub enum RigProvider {
    /// Claude (Anthropic) provider - ANTHROPIC_API_KEY
    Claude(anthropic::Client),
    /// OpenAI provider - OPENAI_API_KEY
    OpenAI(openai::Client),
    /// Mistral provider - MISTRAL_API_KEY
    Mistral(mistral::Client),
    /// Groq provider - GROQ_API_KEY
    Groq(groq::Client),
    /// DeepSeek provider - DEEPSEEK_API_KEY
    DeepSeek(deepseek::Client),
    /// Gemini (Google) provider - GEMINI_API_KEY
    Gemini(gemini::Client),
    /// xAI (Grok) provider - XAI_API_KEY
    XAi(xai::Client),
    /// Native local provider - GGUF models via mistral.rs
    /// Requires `native-inference` feature and explicit model loading.
    /// Now uses NativeRuntime directly with full streaming support.
    #[cfg(feature = "native-inference")]
    Native(super::native::NativeRuntime),
}

impl RigProvider {
    /// Create a RigProvider by name or alias, with env var validation.
    ///
    /// Resolves aliases via `core::find_provider()` (e.g., "claude" -> "anthropic"),
    /// checks that the required env var is set, and returns the appropriate variant.
    ///
    /// # Errors
    ///
    /// - `NikaError::MissingApiKey` if the provider requires a key and the env var is not set
    /// - `NikaError::ProviderNotConfigured` if the provider name is unknown
    pub fn from_name(name: &str) -> Result<Self, crate::error::NikaError> {
        let provider = crate::core::find_provider(name).ok_or_else(|| {
            crate::error::NikaError::ProviderNotConfigured {
                provider: name.to_string(),
            }
        })?;

        // Check env var is set (rig-core panics without it)
        if provider.requires_key && !provider.has_env_key() {
            return Err(crate::error::NikaError::MissingApiKey {
                provider: provider.id.to_string(),
            });
        }

        match provider.id {
            "anthropic" => Ok(Self::claude()),
            "openai" => Ok(Self::openai()),
            "mistral" => Ok(Self::mistral()),
            "groq" => Ok(Self::groq()),
            "deepseek" => Ok(Self::deepseek()),
            "gemini" => Ok(Self::gemini()),
            "xai" => Ok(Self::xai()),
            #[cfg(feature = "native-inference")]
            "native" => Ok(Self::native()),
            _ => Err(crate::error::NikaError::ProviderNotConfigured {
                provider: name.to_string(),
            }),
        }
    }

    /// Create a Claude provider from environment variable ANTHROPIC_API_KEY
    pub fn claude() -> Self {
        let client = anthropic::Client::from_env();
        RigProvider::Claude(client)
    }

    /// Create an OpenAI provider from environment variable OPENAI_API_KEY
    pub fn openai() -> Self {
        let client = openai::Client::from_env();
        RigProvider::OpenAI(client)
    }

    /// Create a Mistral provider from environment variable MISTRAL_API_KEY
    pub fn mistral() -> Self {
        let client = mistral::Client::from_env();
        RigProvider::Mistral(client)
    }

    /// Create a Groq provider from environment variable GROQ_API_KEY
    pub fn groq() -> Self {
        let client = groq::Client::from_env();
        RigProvider::Groq(client)
    }

    /// Create a DeepSeek provider from environment variable DEEPSEEK_API_KEY
    pub fn deepseek() -> Self {
        let client = deepseek::Client::from_env();
        RigProvider::DeepSeek(client)
    }

    /// Create a Gemini (Google) provider from environment variable GEMINI_API_KEY
    pub fn gemini() -> Self {
        let client = gemini::Client::from_env();
        RigProvider::Gemini(client)
    }

    /// Create an xAI (Grok) provider from environment variable XAI_API_KEY
    pub fn xai() -> Self {
        let client = xai::Client::from_env();
        RigProvider::XAi(client)
    }

    /// Create a Native provider for local GGUF inference
    ///
    /// The provider is created without a model loaded. Call `load_native_model()`
    /// before running inference.
    ///
    /// Now uses NativeRuntime directly with full streaming support.
    ///
    /// Requires the `native-inference` feature.
    #[cfg(feature = "native-inference")]
    pub fn native() -> Self {
        RigProvider::Native(super::native::NativeRuntime::new())
    }

    /// Load a model for native inference.
    ///
    /// Only valid for `RigProvider::Native`. Returns an error for other providers.
    ///
    /// # Arguments
    /// * `model_path` - Path to the GGUF model file
    /// * `config` - Optional load configuration (context size, GPU layers, etc.)
    #[cfg(feature = "native-inference")]
    pub async fn load_native_model(
        &mut self,
        model_path: impl Into<std::path::PathBuf>,
        config: Option<super::native::LoadConfig>,
    ) -> Result<(), RigInferError> {
        match self {
            RigProvider::Native(runtime) => runtime
                .load(model_path.into(), config.unwrap_or_default())
                .await
                .map_err(|e: super::native::NativeError| RigInferError::PromptError(e.to_string())),
            _ => Err(RigInferError::PromptError(
                "load_native_model only valid for Native provider".to_string(),
            )),
        }
    }

    /// Check if native model is loaded.
    #[cfg(feature = "native-inference")]
    pub fn is_native_loaded(&self) -> bool {
        match self {
            RigProvider::Native(runtime) => runtime.is_loaded(),
            _ => false,
        }
    }

    /// Get the provider name
    pub fn name(&self) -> &'static str {
        match self {
            RigProvider::Claude(_) => "claude",
            RigProvider::OpenAI(_) => "openai",
            RigProvider::Mistral(_) => "mistral",
            RigProvider::Groq(_) => "groq",
            RigProvider::DeepSeek(_) => "deepseek",
            RigProvider::Gemini(_) => "gemini",
            RigProvider::XAi(_) => "xai",
            #[cfg(feature = "native-inference")]
            RigProvider::Native(_) => "native",
        }
    }

    /// Get the default model for this provider
    ///
    /// | Provider | Model | Notes |
    /// |----------|-------|-------|
    /// | Claude | claude-sonnet-4-6 | Latest stable (Feb 2026) |
    /// | OpenAI | gpt-4o | Latest stable |
    /// | Mistral | mistral-large-latest | Best for complex tasks |
    /// | Groq | llama-3.3-70b-versatile | Fast inference |
    /// | DeepSeek | deepseek-chat | Cost-effective |
    /// | Gemini | gemini-2.0-flash | Latest stable |
    /// | Native | (loaded model) | Uses pre-loaded GGUF model |
    pub fn default_model(&self) -> &'static str {
        match self {
            // Note: rig-core's CLAUDE_3_5_SONNET constant is outdated
            // Using explicit model name for stability
            RigProvider::Claude(_) => "claude-sonnet-4-6",
            RigProvider::OpenAI(_) => openai::GPT_4O,
            RigProvider::Mistral(_) => mistral::MISTRAL_LARGE,
            RigProvider::Groq(_) => "llama-3.3-70b-versatile",
            RigProvider::DeepSeek(_) => "deepseek-chat",
            RigProvider::Gemini(_) => "gemini-2.0-flash",
            RigProvider::XAi(_) => "grok-3-fast",
            // Native uses whatever model is loaded, no default
            #[cfg(feature = "native-inference")]
            RigProvider::Native(_) => "native-model",
        }
    }

    /// Simple text completion (infer) using rig-core
    ///
    /// # Arguments
    /// * `prompt` - The text prompt to send
    /// * `model` - Model identifier (uses default if None)
    ///
    /// # Returns
    /// The completion text from the model
    pub async fn infer(&self, prompt: &str, model: Option<&str>) -> Result<String, RigInferError> {
        let model_id = model.unwrap_or_else(|| self.default_model());

        match self {
            RigProvider::Claude(client) => {
                // Anthropic requires max_tokens to be set explicitly
                let agent = client.agent(model_id).max_tokens(8192).build();
                agent
                    .prompt(prompt)
                    .await
                    .map_err(|e: PromptError| RigInferError::PromptError(e.to_string()))
            }
            RigProvider::OpenAI(client) => {
                let agent = client.agent(model_id).max_tokens(8192).build();
                agent
                    .prompt(prompt)
                    .await
                    .map_err(|e: PromptError| RigInferError::PromptError(e.to_string()))
            }
            RigProvider::Mistral(client) => {
                let agent = client.agent(model_id).max_tokens(8192).build();
                agent
                    .prompt(prompt)
                    .await
                    .map_err(|e: PromptError| RigInferError::PromptError(e.to_string()))
            }
            RigProvider::Groq(client) => {
                let agent = client.agent(model_id).max_tokens(8192).build();
                agent
                    .prompt(prompt)
                    .await
                    .map_err(|e: PromptError| RigInferError::PromptError(e.to_string()))
            }
            RigProvider::DeepSeek(client) => {
                let agent = client.agent(model_id).max_tokens(8192).build();
                agent
                    .prompt(prompt)
                    .await
                    .map_err(|e: PromptError| RigInferError::PromptError(e.to_string()))
            }
            RigProvider::Gemini(client) => {
                let agent = client.agent(model_id).max_tokens(8192).build();
                agent
                    .prompt(prompt)
                    .await
                    .map_err(|e: PromptError| RigInferError::PromptError(e.to_string()))
            }
            RigProvider::XAi(client) => {
                let agent = client.agent(model_id).max_tokens(8192).build();
                agent
                    .prompt(prompt)
                    .await
                    .map_err(|e: PromptError| RigInferError::PromptError(e.to_string()))
            }
            #[cfg(feature = "native-inference")]
            RigProvider::Native(runtime) => {
                // Native inference uses direct API, not rig-core agent
                // Model must be pre-loaded via load_native_model()
                runtime
                    .infer(prompt, super::native::ChatOptions::default())
                    .await
                    .map(|r| r.message.content)
                    .map_err(|e: super::native::NativeError| {
                        RigInferError::PromptError(e.to_string())
                    })
            }
        }
    }

    /// Vision inference: send multimodal content (text + images) to the LLM.
    ///
    /// Builds a `Message::User` with mixed text + base64 image parts,
    /// then uses `agent.prompt(message)` to send it. The agent handles
    /// provider-specific message formatting automatically.
    ///
    /// # Arguments
    /// * `user_content` - Pre-built rig UserContent items (text + images)
    /// * `model` - Optional model override
    /// * `system` - Optional system prompt
    /// * `max_tokens` - Optional max tokens
    ///
    /// # Errors
    /// Returns `RigInferError::VisionNotSupported` for DeepSeek provider.
    /// Native vision requires a VisionHf model to be loaded.
    pub async fn infer_vision(
        &self,
        user_content: Vec<rig::completion::message::UserContent>,
        model: Option<&str>,
        system: Option<&str>,
        max_tokens: Option<u32>,
    ) -> Result<String, RigInferError> {
        use rig::completion::message::Message;
        use rig::OneOrMany;

        // Early return: DeepSeek does not support vision at all
        if matches!(self, RigProvider::DeepSeek(_)) {
            return Err(RigInferError::VisionNotSupported(
                "DeepSeek does not support vision/multimodal content".to_string(),
            ));
        }

        // Early return: Native vision uses NativeRuntime directly (not rig-core)
        #[cfg(feature = "native-inference")]
        if let RigProvider::Native(runtime) = self {
            if !runtime.supports_vision() {
                return Err(RigInferError::VisionNotSupported(
                    "Native model does not support vision. Load a vision model via \
                     NativeModelKind::VisionHf (e.g., `nika model vision <model_id> --isq Q4K`)"
                        .to_string(),
                ));
            }
            let (prompt_text, vision_images) = extract_native_vision_parts(&user_content)?;
            let options = super::native::ChatOptions {
                max_tokens,
                ..Default::default()
            };
            let response = runtime
                .infer_vision(&prompt_text, vision_images, options)
                .await
                .map_err(|e: super::native::NativeError| {
                    RigInferError::PromptError(e.to_string())
                })?;
            return Ok(response.message.content);
        }

        let model_id = model.unwrap_or_else(|| self.default_model());
        let max_tok = max_tokens.map(u64::from).unwrap_or(8192);

        let message = Message::User {
            content: OneOrMany::many(user_content).map_err(|_| {
                RigInferError::VisionNotSupported("content parts list is empty".to_string())
            })?,
        };

        macro_rules! vision_prompt {
            ($client:expr) => {{
                let mut builder = $client.agent(model_id).max_tokens(max_tok);
                if let Some(sys) = system {
                    builder = builder.preamble(sys);
                }
                let agent = builder.build();
                agent
                    .prompt(message)
                    .await
                    .map_err(|e: PromptError| RigInferError::PromptError(e.to_string()))
            }};
        }

        match self {
            RigProvider::Claude(client) => vision_prompt!(client),
            RigProvider::OpenAI(client) => vision_prompt!(client),
            RigProvider::Mistral(client) => vision_prompt!(client),
            RigProvider::Groq(client) => vision_prompt!(client),
            RigProvider::Gemini(client) => vision_prompt!(client),
            RigProvider::XAi(client) => vision_prompt!(client),
            // DeepSeek and Native handled above via early returns
            RigProvider::DeepSeek(_) => unreachable!("DeepSeek handled above"),
            #[cfg(feature = "native-inference")]
            RigProvider::Native(_) => unreachable!("Native handled above"),
        }
    }

    /// Vision inference with streaming output.
    ///
    /// Same as `infer_vision` but streams response tokens via an mpsc channel.
    /// Native vision uses a non-streaming fallback (sends full response as Done chunk).
    pub async fn infer_vision_stream(
        &self,
        user_content: Vec<rig::completion::message::UserContent>,
        tx: mpsc::Sender<StreamChunk>,
        model: Option<&str>,
        system: Option<&str>,
        max_tokens: Option<u32>,
    ) -> Result<StreamResult, RigInferError> {
        use rig::completion::message::Message;
        use rig::OneOrMany;

        // Early return: DeepSeek does not support vision at all
        if matches!(self, RigProvider::DeepSeek(_)) {
            return Err(RigInferError::VisionNotSupported(
                "DeepSeek does not support vision/multimodal content".to_string(),
            ));
        }

        // Early return: Native vision — non-streaming fallback via NativeRuntime
        // NativeRuntime.infer_vision_stream() exists but rig's StreamChunk protocol
        // differs from the native mpsc stream, so we use non-streaming + Done chunk.
        #[cfg(feature = "native-inference")]
        if let RigProvider::Native(runtime) = self {
            if !runtime.supports_vision() {
                return Err(RigInferError::VisionNotSupported(
                    "Native model does not support vision. Load a vision model via \
                     NativeModelKind::VisionHf (e.g., `nika model vision <model_id> --isq Q4K`)"
                        .to_string(),
                ));
            }
            let (prompt_text, vision_images) = extract_native_vision_parts(&user_content)?;
            let options = super::native::ChatOptions {
                max_tokens,
                ..Default::default()
            };
            let response = runtime
                .infer_vision(&prompt_text, vision_images, options)
                .await
                .map_err(|e: super::native::NativeError| {
                    RigInferError::PromptError(e.to_string())
                })?;
            // Send full response as a single Done chunk (non-streaming fallback)
            let text = response.message.content;
            let _ = tx.send(StreamChunk::Done(text.clone())).await;
            return Ok(StreamResult {
                text,
                ..Default::default()
            });
        }

        let model_id = model.unwrap_or_else(|| self.default_model());
        let max_tok = max_tokens.map(u64::from).unwrap_or(8192);

        let message = Message::User {
            content: OneOrMany::many(user_content).map_err(|_| {
                RigInferError::VisionNotSupported("content parts list is empty".to_string())
            })?,
        };

        let mut response_parts: Vec<String> = Vec::new();
        let mut result = StreamResult::default();

        macro_rules! vision_stream {
            ($client:expr, $is_anthropic:expr) => {{
                let model = $client.completion_model(model_id);
                let mut builder = model.completion_request(message).max_tokens(max_tok);
                if let Some(sys) = system {
                    builder = builder.preamble(sys.to_string());
                }
                let request = builder.build();
                let mut stream = model
                    .stream(request)
                    .await
                    .map_err(|e| RigInferError::PromptError(e.to_string()))?;
                consume_rig_stream(
                    &mut stream,
                    &tx,
                    &mut response_parts,
                    &mut result,
                    $is_anthropic,
                )
                .await?;
            }};
        }

        match self {
            RigProvider::Claude(client) => vision_stream!(client, true),
            RigProvider::OpenAI(client) => vision_stream!(client, false),
            RigProvider::Mistral(client) => vision_stream!(client, false),
            RigProvider::Groq(client) => vision_stream!(client, false),
            RigProvider::Gemini(client) => vision_stream!(client, false),
            RigProvider::XAi(client) => vision_stream!(client, false),
            // DeepSeek and Native handled above via early returns
            RigProvider::DeepSeek(_) => unreachable!("DeepSeek handled above"),
            #[cfg(feature = "native-inference")]
            RigProvider::Native(_) => unreachable!("Native handled above"),
        }

        result.text = response_parts.join("");
        Ok(result)
    }

    /// Infer with injected tools for structured output enforcement.
    ///
    /// Builds a single-turn agent with the given tools and `tool_choice: Required`.
    /// The LLM is forced to call one of the injected tools, returning structured output
    /// as the tool call arguments. Used by DynamicSubmitTool (Layer 0).
    ///
    /// # Arguments
    /// * `prompt` - The text prompt to send
    /// * `tools` - Tools to inject (typically a single DynamicSubmitTool)
    /// * `model` - Optional model override
    /// * `max_tokens` - Optional max tokens for the response (default: 8192)
    ///
    /// # Returns
    /// The tool call arguments as a string (the structured JSON output)
    pub async fn infer_with_tools(
        &self,
        prompt: &str,
        tools: Vec<Box<dyn ToolDyn>>,
        model: Option<&str>,
        max_tokens: Option<u32>,
        system: Option<&str>,
    ) -> Result<String, RigInferError> {
        use rig::agent::AgentBuilder;
        use rig::message::ToolChoice as RigToolChoice;

        let model_id = model.unwrap_or_else(|| self.default_model());
        let max_tok = max_tokens.map(|v| v as u64).unwrap_or(8192);

        macro_rules! build_agent_with_tools {
            ($client:expr) => {{
                let mut builder = AgentBuilder::new($client.completion_model(model_id))
                    .tools(tools)
                    .tool_choice(RigToolChoice::Required)
                    .max_tokens(max_tok);
                if let Some(sys) = system {
                    builder = builder.preamble(sys);
                }
                let agent = builder.build();
                agent
                    .prompt(prompt)
                    .await
                    .map_err(|e: PromptError| RigInferError::PromptError(e.to_string()))
            }};
        }

        match self {
            RigProvider::Claude(client) => build_agent_with_tools!(client),
            RigProvider::OpenAI(client) => build_agent_with_tools!(client),
            RigProvider::Mistral(client) => build_agent_with_tools!(client),
            RigProvider::Groq(client) => build_agent_with_tools!(client),
            RigProvider::DeepSeek(client) => build_agent_with_tools!(client),
            RigProvider::Gemini(client) => build_agent_with_tools!(client),
            RigProvider::XAi(client) => build_agent_with_tools!(client),
            #[cfg(feature = "native-inference")]
            RigProvider::Native(_) => {
                // Native inference doesn't support tool calling
                Err(RigInferError::PromptError(
                    "Native inference does not support tool-based structured output".to_string(),
                ))
            }
        }
    }

    /// Text completion with full control over LLM parameters
    ///
    /// # Arguments
    /// * `prompt` - The text prompt to send
    /// * `options` - LLM control options (model, temperature, max_tokens, system)
    ///
    /// # Returns
    /// The completion text from the model
    ///
    /// # Example
    /// ```ignore
    /// let options = InferOptions {
    ///     temperature: Some(0.7),
    ///     max_tokens: Some(2000),
    ///     system: Some("You are a helpful assistant.".to_string()),
    ///     ..Default::default()
    /// };
    /// let result = provider.infer_with_options("Explain Rust", &options).await?;
    /// ```
    pub async fn infer_with_options(
        &self,
        prompt: &str,
        options: &InferOptions,
    ) -> Result<String, RigInferError> {
        let model_id = options
            .model
            .as_deref()
            .unwrap_or_else(|| self.default_model());
        let max_tokens = options.max_tokens.unwrap_or(8192);

        // Use system prompt as preamble (not concatenated into user prompt)
        let user_prompt = prompt.to_string();

        match self {
            RigProvider::Claude(client) => {
                let mut builder = client.agent(model_id).max_tokens(max_tokens as u64);
                if let Some(system) = &options.system {
                    builder = builder.preamble(system);
                }
                if let Some(temp) = options.temperature {
                    builder = builder.temperature(temp);
                }
                let agent = builder.build();
                agent
                    .prompt(&user_prompt)
                    .await
                    .map_err(|e: PromptError| RigInferError::PromptError(e.to_string()))
            }
            RigProvider::OpenAI(client) => {
                let mut builder = client.agent(model_id).max_tokens(max_tokens as u64);
                if let Some(system) = &options.system {
                    builder = builder.preamble(system);
                }
                if let Some(temp) = options.temperature {
                    builder = builder.temperature(temp);
                }
                let agent = builder.build();
                agent
                    .prompt(&user_prompt)
                    .await
                    .map_err(|e: PromptError| RigInferError::PromptError(e.to_string()))
            }
            RigProvider::Mistral(client) => {
                let mut builder = client.agent(model_id).max_tokens(max_tokens as u64);
                if let Some(system) = &options.system {
                    builder = builder.preamble(system);
                }
                if let Some(temp) = options.temperature {
                    builder = builder.temperature(temp);
                }
                let agent = builder.build();
                agent
                    .prompt(&user_prompt)
                    .await
                    .map_err(|e: PromptError| RigInferError::PromptError(e.to_string()))
            }
            RigProvider::Groq(client) => {
                let mut builder = client.agent(model_id).max_tokens(max_tokens as u64);
                if let Some(system) = &options.system {
                    builder = builder.preamble(system);
                }
                if let Some(temp) = options.temperature {
                    builder = builder.temperature(temp);
                }
                let agent = builder.build();
                agent
                    .prompt(&user_prompt)
                    .await
                    .map_err(|e: PromptError| RigInferError::PromptError(e.to_string()))
            }
            RigProvider::DeepSeek(client) => {
                let mut builder = client.agent(model_id).max_tokens(max_tokens as u64);
                if let Some(system) = &options.system {
                    builder = builder.preamble(system);
                }
                if let Some(temp) = options.temperature {
                    builder = builder.temperature(temp);
                }
                let agent = builder.build();
                agent
                    .prompt(&user_prompt)
                    .await
                    .map_err(|e: PromptError| RigInferError::PromptError(e.to_string()))
            }
            RigProvider::Gemini(client) => {
                let mut builder = client.agent(model_id).max_tokens(max_tokens as u64);
                if let Some(system) = &options.system {
                    builder = builder.preamble(system);
                }
                if let Some(temp) = options.temperature {
                    builder = builder.temperature(temp);
                }
                let agent = builder.build();
                agent
                    .prompt(&user_prompt)
                    .await
                    .map_err(|e: PromptError| RigInferError::PromptError(e.to_string()))
            }
            RigProvider::XAi(client) => {
                let mut builder = client.agent(model_id).max_tokens(max_tokens as u64);
                if let Some(system) = &options.system {
                    builder = builder.preamble(system);
                }
                if let Some(temp) = options.temperature {
                    builder = builder.temperature(temp);
                }
                let agent = builder.build();
                agent
                    .prompt(&user_prompt)
                    .await
                    .map_err(|e: PromptError| RigInferError::PromptError(e.to_string()))
            }
            #[cfg(feature = "native-inference")]
            RigProvider::Native(runtime) => {
                // Native inference uses ChatOptions from native module
                let chat_options = super::native::ChatOptions {
                    temperature: options.temperature.map(|t| t as f32),
                    max_tokens: options.max_tokens,
                    ..Default::default()
                };
                runtime
                    .infer(&user_prompt, chat_options)
                    .await
                    .map(|r| r.message.content)
                    .map_err(|e: super::native::NativeError| {
                        RigInferError::PromptError(e.to_string())
                    })
            }
        }
    }

    /// Auto-detect and create a provider from available environment variables
    ///
    /// Provider detection order:
    /// 1. ANTHROPIC_API_KEY → Claude
    /// 2. OPENAI_API_KEY → OpenAI
    /// 3. MISTRAL_API_KEY → Mistral
    /// 4. GROQ_API_KEY → Groq
    /// 5. DEEPSEEK_API_KEY → DeepSeek
    /// 6. GEMINI_API_KEY → Gemini
    /// 7. NIKA_NATIVE_MODEL → Native
    ///
    /// Returns None if no provider is available.
    /// Empty env vars are treated as unset.
    pub fn auto() -> Option<Self> {
        use crate::core::providers::{ProviderCategory, KNOWN_PROVIDERS};

        // Iterate KNOWN_PROVIDERS in priority order (LLM providers first, then native)
        for p in KNOWN_PROVIDERS.iter() {
            if p.category == ProviderCategory::Llm && p.has_env_key() {
                return match p.id {
                    "anthropic" => Some(Self::claude()),
                    "openai" => Some(Self::openai()),
                    "mistral" => Some(Self::mistral()),
                    "groq" => Some(Self::groq()),
                    "deepseek" => Some(Self::deepseek()),
                    "gemini" => Some(Self::gemini()),
                    "xai" => Some(Self::xai()),
                    _ => continue,
                };
            }
        }
        // Native is opt-in: requires NIKA_NATIVE_MODEL to be set
        #[cfg(feature = "native-inference")]
        if std::env::var("NIKA_NATIVE_MODEL").is_ok_and(|v| !v.trim().is_empty()) {
            return Some(Self::native());
        }
        None
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Provider Health Check & Verification
    // ═══════════════════════════════════════════════════════════════════════════

    /// Verify the provider connection is working
    ///
    /// Makes a minimal API call to check:
    /// - API key is valid
    /// - Network connectivity works
    /// - Provider service is responding
    ///
    /// Returns Ok(VerifyResult) with latency on success,
    /// or Err with specific reason on failure.
    pub async fn verify(&self) -> Result<ProviderVerifyResult, ProviderVerifyError> {
        use std::time::Instant;

        let start = Instant::now();

        // Use a minimal prompt to test connectivity
        let test_prompt = "Hi";

        match self.infer(test_prompt, None).await {
            Ok(_) => Ok(ProviderVerifyResult {
                provider: self.name().to_string(),
                latency: start.elapsed(),
                model: self.default_model().to_string(),
            }),
            Err(e) => {
                let error_msg = e.to_string().to_lowercase();

                // Categorize the error
                if error_msg.contains("401")
                    || error_msg.contains("unauthorized")
                    || error_msg.contains("invalid api key")
                    || error_msg.contains("authentication")
                {
                    Err(ProviderVerifyError::InvalidApiKey {
                        provider: self.name().to_string(),
                    })
                } else if error_msg.contains("rate limit")
                    || error_msg.contains("429")
                    || error_msg.contains("too many requests")
                {
                    Err(ProviderVerifyError::RateLimited {
                        provider: self.name().to_string(),
                    })
                } else if error_msg.contains("timeout")
                    || error_msg.contains("timed out")
                    || error_msg.contains("deadline")
                {
                    Err(ProviderVerifyError::Timeout {
                        provider: self.name().to_string(),
                    })
                } else if error_msg.contains("connection")
                    || error_msg.contains("network")
                    || error_msg.contains("dns")
                    || error_msg.contains("refused")
                {
                    Err(ProviderVerifyError::NetworkError {
                        provider: self.name().to_string(),
                        details: e.to_string(),
                    })
                } else {
                    Err(ProviderVerifyError::ProviderError {
                        provider: self.name().to_string(),
                        details: e.to_string(),
                    })
                }
            }
        }
    }

    /// Quick check if provider credentials are configured
    ///
    /// This is a fast, synchronous check that doesn't make network calls.
    /// Use `verify()` for actual connection testing.
    pub fn is_configured(&self) -> bool {
        let has_key = |key: &str| std::env::var(key).is_ok_and(|v| !v.trim().is_empty());

        match self {
            RigProvider::Claude(_) => has_key("ANTHROPIC_API_KEY"),
            RigProvider::OpenAI(_) => has_key("OPENAI_API_KEY"),
            RigProvider::Mistral(_) => has_key("MISTRAL_API_KEY"),
            RigProvider::Groq(_) => has_key("GROQ_API_KEY"),
            RigProvider::DeepSeek(_) => has_key("DEEPSEEK_API_KEY"),
            RigProvider::Gemini(_) => has_key("GEMINI_API_KEY"),
            RigProvider::XAi(_) => has_key("XAI_API_KEY"),
            #[cfg(feature = "native-inference")]
            RigProvider::Native(_) => {
                // Native doesn't need API key, but requires model to be loaded
                // Use is_native_loaded() to check if ready for inference
                true
            }
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Provider Verification Types
// ═══════════════════════════════════════════════════════════════════════════

/// Result of a successful provider verification
#[derive(Debug, Clone)]
pub struct ProviderVerifyResult {
    /// Provider name (claude, openai, etc.)
    pub provider: String,
    /// Round-trip latency for the test call
    pub latency: std::time::Duration,
    /// Model used for verification
    pub model: String,
}

/// Error during provider verification
#[derive(Debug, Clone, thiserror::Error)]
pub enum ProviderVerifyError {
    #[error("Invalid API key for {provider}")]
    InvalidApiKey { provider: String },

    #[error("Rate limited by {provider}")]
    RateLimited { provider: String },

    #[error("Connection timeout to {provider}")]
    Timeout { provider: String },

    #[error("Network error connecting to {provider}: {details}")]
    NetworkError { provider: String, details: String },

    #[error("Provider error from {provider}: {details}")]
    ProviderError { provider: String, details: String },
}

impl ProviderVerifyError {
    /// Get a user-friendly suggestion for fixing the error
    pub fn suggestion(&self) -> &'static str {
        match self {
            ProviderVerifyError::InvalidApiKey { .. } => {
                "Check your API key in environment variables"
            }
            ProviderVerifyError::RateLimited { .. } => {
                "Wait a moment and try again, or check your plan limits"
            }
            ProviderVerifyError::Timeout { .. } => "Check your network connection or try again",
            ProviderVerifyError::NetworkError { .. } => {
                "Check your internet connection and firewall settings"
            }
            ProviderVerifyError::ProviderError { .. } => {
                "The provider service may be experiencing issues"
            }
        }
    }
}

/// Error type for RigProvider infer operations
#[derive(Debug, thiserror::Error)]
pub enum RigInferError {
    #[error("Completion error: {0}")]
    PromptError(String),

    /// Stream timeout - no chunk received within timeout period
    #[error("Stream timeout: no chunk received for {duration_ms}ms")]
    Timeout { duration_ms: u64 },

    /// Provider does not support vision/multimodal content
    #[error("Vision not supported: {0}")]
    VisionNotSupported(String),
}

// =============================================================================
// StreamChunk - Communication type for streaming responses
// =============================================================================

/// Chunk of streaming response for real-time display
#[derive(Debug, Clone)]
pub enum StreamChunk {
    /// Text token from the model
    Token(String),
    /// Thinking/reasoning content (Claude extended thinking)
    Thinking(String),
    /// Stream completed successfully with final text
    Done(String),
    /// Stream failed with error
    Error(String),
    /// Token usage metrics (sent after completion)
    Metrics {
        input_tokens: u64,
        output_tokens: u64,
    },
    /// MCP server connected successfully
    McpConnected(String),
    /// MCP server connection failed
    McpError { server_name: String, error: String },
    // ═══════════════════════════════════════════════════════════════════════════
    // Chat Inline Box Events
    // ═══════════════════════════════════════════════════════════════════════════
    /// MCP tool call started (for inline visualization)
    McpCallStart {
        tool: String,
        server: String,
        params: String,
    },
    /// MCP tool call completed successfully
    McpCallComplete { result: String },
    /// MCP tool call failed
    McpCallFailed { error: String },
    /// Infer stream started (for inline visualization)
    InferStart {
        model: String,
        /// The user prompt text (for TaskBox::Infer display)
        prompt: String,
        prompt_tokens: u32,
        max_tokens: u32,
    },
    /// Infer stream token count update
    InferTokens { output_tokens: u32 },
    /// Infer stream completed
    InferComplete,
    // ═══════════════════════════════════════════════════════════════════════════
    // Activity Events for /exec, /fetch, /agent
    // ═══════════════════════════════════════════════════════════════════════════
    /// Shell command started (for activity stack)
    ExecStart { command: String },
    /// Shell command completed
    ExecComplete,
    /// HTTP fetch started (for activity stack)
    FetchStart { url: String, method: String },
    /// HTTP fetch completed
    FetchComplete,
    /// Agent loop started (for activity stack)
    AgentStart { goal: String },
    /// Agent loop completed
    AgentComplete,
    // ═══════════════════════════════════════════════════════════════════════════
    // Connection Verification Events
    // ═══════════════════════════════════════════════════════════════════════════
    /// Provider verification started
    ProviderVerifying { provider: String, model: String },
    /// Provider verification succeeded
    ProviderVerified {
        provider: String,
        model: String,
        latency_ms: u64,
    },
    /// Provider verification failed
    ProviderVerifyFailed { provider: String, error: String },
    /// Provider not configured (no API key set)
    ProviderNotConfigured { provider: String },
    /// MCP server ping started
    McpPinging { server: String },
    /// MCP server ping succeeded
    McpPinged {
        server: String,
        latency_ms: u64,
        tool_count: usize,
    },
    /// All provider verifications timed out (no providers available)
    ProviderVerificationTimeout,
    // ═══════════════════════════════════════════════════════════════════════════
    // Native Model Events
    // ═══════════════════════════════════════════════════════════════════════════
    /// Native model pull started
    NativeModelPullStarted { model: String },
    /// Native model pull progress update
    NativeModelPullProgress {
        model: String,
        status: String,
        completed: u64,
        total: u64,
    },
    /// Native model pull completed successfully
    NativeModelPulled {
        model: String,
        path: String,
        size: u64,
    },
    /// Native model pull failed
    NativeModelPullFailed { model: String, error: String },
    /// Native model deleted
    NativeModelDeleted { model: String },
    /// Native model delete failed
    NativeModelDeleteFailed { model: String, error: String },
    /// Native models list refreshed
    NativeModelsRefreshed { count: usize },
}

// =============================================================================
// StreamResult - Complete streaming response with token usage
// =============================================================================

/// Complete streaming response with text and token usage metrics
#[derive(Debug, Clone, Default)]
pub struct StreamResult {
    /// The complete response text
    pub text: String,
    /// Number of input tokens used
    pub input_tokens: u64,
    /// Number of output tokens generated
    pub output_tokens: u64,
    /// Total tokens (input + output)
    pub total_tokens: u64,
    /// Cached input tokens (from prompt caching)
    pub cached_input_tokens: u64,
}

impl StreamResult {
    /// Create a new StreamResult with just text (zero tokens)
    pub fn from_text(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            ..Default::default()
        }
    }
}

/// Consume a rig-core streaming response, forwarding chunks to the channel.
///
/// Shared streaming loop for all rig-core providers. Handles:
/// - Per-chunk timeout via `STREAM_CHUNK_TIMEOUT`
/// - Token text forwarding via `StreamChunk::Token`
/// - Optional thinking/reasoning capture (Claude only)
/// - Token usage extraction from `Final` response
///
/// Returns early on timeout or stream error.
async fn consume_rig_stream<R>(
    stream: &mut rig::streaming::StreamingCompletionResponse<R>,
    tx: &mpsc::Sender<StreamChunk>,
    response_parts: &mut Vec<String>,
    result: &mut StreamResult,
    capture_thinking: bool,
) -> Result<(), RigInferError>
where
    R: Clone + Unpin + GetTokenUsage + serde::Serialize + serde::de::DeserializeOwned,
{
    loop {
        let chunk_result = match timeout(STREAM_CHUNK_TIMEOUT, stream.next()).await {
            Ok(Some(result)) => result,
            Ok(None) => break,
            Err(_elapsed) => {
                let _ = tx.try_send(StreamChunk::Error(format!(
                    "Stream timeout: no chunk received for {}s",
                    STREAM_CHUNK_TIMEOUT.as_secs()
                )));
                return Err(RigInferError::Timeout {
                    duration_ms: STREAM_CHUNK_TIMEOUT.as_millis() as u64,
                });
            }
        };

        match chunk_result {
            Ok(content) => match content {
                StreamedAssistantContent::Text(text) => {
                    response_parts.push(text.text.clone());
                    let _ = tx.try_send(StreamChunk::Token(text.text));
                }
                StreamedAssistantContent::ReasoningDelta { reasoning, .. } if capture_thinking => {
                    let _ = tx.try_send(StreamChunk::Thinking(reasoning));
                }
                StreamedAssistantContent::Final(response) => {
                    if let Some(usage) = response.token_usage() {
                        result.input_tokens = usage.input_tokens;
                        result.output_tokens = usage.output_tokens;
                        result.total_tokens = usage.total_tokens;
                        result.cached_input_tokens = usage.cached_input_tokens;
                    }
                }
                _ => {}
            },
            Err(e) => {
                let _ = tx.try_send(StreamChunk::Error(e.to_string()));
                return Err(RigInferError::PromptError(e.to_string()));
            }
        }
    }
    Ok(())
}

impl RigProvider {
    /// Stream text completion with real-time token updates
    ///
    /// Sends tokens to the provided channel as they arrive from the model.
    /// This enables real-time display in the TUI like Claude Code / Gemini.
    ///
    /// # Arguments
    /// * `prompt` - The text prompt to send
    /// * `tx` - Channel sender for streaming chunks
    ///
    /// # Returns
    /// `StreamResult` containing complete response text and token usage metrics
    pub async fn infer_stream(
        &self,
        prompt: &str,
        tx: mpsc::Sender<StreamChunk>,
        model: Option<&str>,
    ) -> Result<StreamResult, RigInferError> {
        let model_id = model.unwrap_or_else(|| self.default_model());
        let mut response_parts: Vec<String> = Vec::new();
        let mut result = StreamResult::default();

        match self {
            RigProvider::Claude(client) => {
                let model = client.completion_model(model_id);
                let request = model.completion_request(prompt).max_tokens(8192).build();
                let mut stream = model
                    .stream(request)
                    .await
                    .map_err(|e| RigInferError::PromptError(e.to_string()))?;
                consume_rig_stream(&mut stream, &tx, &mut response_parts, &mut result, true)
                    .await?;
            }
            RigProvider::OpenAI(client) => {
                let model = client.completion_model(model_id);
                let request = model.completion_request(prompt).max_tokens(8192).build();
                let mut stream = model
                    .stream(request)
                    .await
                    .map_err(|e| RigInferError::PromptError(e.to_string()))?;
                consume_rig_stream(&mut stream, &tx, &mut response_parts, &mut result, false)
                    .await?;
            }
            RigProvider::Mistral(client) => {
                let model = client.completion_model(model_id);
                let request = model.completion_request(prompt).max_tokens(8192).build();
                let mut stream = model
                    .stream(request)
                    .await
                    .map_err(|e| RigInferError::PromptError(e.to_string()))?;
                consume_rig_stream(&mut stream, &tx, &mut response_parts, &mut result, false)
                    .await?;
            }
            RigProvider::Groq(client) => {
                let model = client.completion_model(model_id);
                let request = model.completion_request(prompt).max_tokens(8192).build();
                let mut stream = model
                    .stream(request)
                    .await
                    .map_err(|e| RigInferError::PromptError(e.to_string()))?;
                consume_rig_stream(&mut stream, &tx, &mut response_parts, &mut result, false)
                    .await?;
            }
            RigProvider::DeepSeek(client) => {
                let model = client.completion_model(model_id);
                let request = model.completion_request(prompt).max_tokens(8192).build();
                let mut stream = model
                    .stream(request)
                    .await
                    .map_err(|e| RigInferError::PromptError(e.to_string()))?;
                consume_rig_stream(&mut stream, &tx, &mut response_parts, &mut result, false)
                    .await?;
            }
            RigProvider::Gemini(client) => {
                let model = client.completion_model(model_id);
                let request = model.completion_request(prompt).max_tokens(8192).build();
                let mut stream = model
                    .stream(request)
                    .await
                    .map_err(|e| RigInferError::PromptError(e.to_string()))?;
                consume_rig_stream(&mut stream, &tx, &mut response_parts, &mut result, false)
                    .await?;
            }
            RigProvider::XAi(client) => {
                let model = client.completion_model(model_id);
                let request = model.completion_request(prompt).max_tokens(8192).build();
                let mut stream = model
                    .stream(request)
                    .await
                    .map_err(|e| RigInferError::PromptError(e.to_string()))?;
                consume_rig_stream(&mut stream, &tx, &mut response_parts, &mut result, false)
                    .await?;
            }
            // Native provider - uses infer_stream() for true token-by-token streaming
            #[cfg(feature = "native-inference")]
            RigProvider::Native(runtime) => {
                use futures::StreamExt;
                use std::pin::pin;

                // Native inference now supports streaming via mistral.rs
                let stream = runtime
                    .infer_stream(prompt, super::native::ChatOptions::default())
                    .await
                    .map_err(|e: super::native::NativeError| {
                        RigInferError::PromptError(e.to_string())
                    })?;

                // Pin the stream for iteration (async_stream produces !Unpin streams)
                let mut stream = pin!(stream);

                // Collect tokens as they arrive (Stream yields Result<String, NativeError>)
                while let Some(result) = stream.next().await {
                    match result {
                        Ok(token) => {
                            response_parts.push(token.clone());
                            let _ = tx.try_send(StreamChunk::Token(token));
                        }
                        Err(e) => {
                            let _ = tx.try_send(StreamChunk::Error(e.to_string()));
                            return Err(RigInferError::PromptError(e.to_string()));
                        }
                    }
                }

                // Note: Token counts not available in streaming mode
                // They would require post-hoc tokenization
            }
        }

        let complete_response = response_parts.concat();
        let _ = tx.try_send(StreamChunk::Done(complete_response.clone()));

        // Send metrics after Done - use try_send to avoid blocking
        let _ = tx.try_send(StreamChunk::Metrics {
            input_tokens: result.input_tokens,
            output_tokens: result.output_tokens,
        });

        result.text = complete_response;
        Ok(result)
    }

    /// Stream inference with LLM control options
    ///
    /// Similar to `infer_stream` but accepts `InferOptions` for temperature,
    /// max_tokens, and system prompt control.
    ///
    /// # Arguments
    /// * `prompt` - The user prompt text
    /// * `tx` - Channel sender for streaming chunks
    /// * `options` - LLM control options (temperature, max_tokens, system)
    ///
    /// # Returns
    /// `StreamResult` containing complete response text and token usage metrics
    pub async fn infer_stream_with_options(
        &self,
        prompt: &str,
        tx: mpsc::Sender<StreamChunk>,
        options: &InferOptions,
    ) -> Result<StreamResult, RigInferError> {
        let model_id = options
            .model
            .as_deref()
            .unwrap_or_else(|| self.default_model());
        let max_tokens = options.max_tokens.unwrap_or(8192);
        let mut response_parts: Vec<String> = Vec::new();
        let mut result = StreamResult::default();

        // Helper: build request with options and start streaming
        // Uses preamble() for system prompt (not string concatenation) to ensure
        // providers treat it as a system message, not user text.
        macro_rules! build_request_with_options {
            ($client:expr) => {{
                let model = $client.completion_model(model_id);
                let mut rb = model
                    .completion_request(prompt)
                    .max_tokens(max_tokens as u64);
                if let Some(ref system) = options.system {
                    rb = rb.preamble(system.clone());
                }
                if let Some(temp) = options.temperature {
                    rb = rb.temperature(temp);
                }
                model
                    .stream(rb.build())
                    .await
                    .map_err(|e| RigInferError::PromptError(e.to_string()))?
            }};
        }

        match self {
            RigProvider::Claude(client) => {
                let mut stream = build_request_with_options!(client);
                consume_rig_stream(&mut stream, &tx, &mut response_parts, &mut result, true)
                    .await?;
            }
            RigProvider::OpenAI(client) => {
                let mut stream = build_request_with_options!(client);
                consume_rig_stream(&mut stream, &tx, &mut response_parts, &mut result, false)
                    .await?;
            }
            RigProvider::Mistral(client) => {
                let mut stream = build_request_with_options!(client);
                consume_rig_stream(&mut stream, &tx, &mut response_parts, &mut result, false)
                    .await?;
            }
            RigProvider::Groq(client) => {
                let mut stream = build_request_with_options!(client);
                consume_rig_stream(&mut stream, &tx, &mut response_parts, &mut result, false)
                    .await?;
            }
            RigProvider::DeepSeek(client) => {
                let mut stream = build_request_with_options!(client);
                consume_rig_stream(&mut stream, &tx, &mut response_parts, &mut result, false)
                    .await?;
            }
            RigProvider::Gemini(client) => {
                let mut stream = build_request_with_options!(client);
                consume_rig_stream(&mut stream, &tx, &mut response_parts, &mut result, false)
                    .await?;
            }
            RigProvider::XAi(client) => {
                let mut stream = build_request_with_options!(client);
                consume_rig_stream(&mut stream, &tx, &mut response_parts, &mut result, false)
                    .await?;
            }
            // Native provider - uses infer_stream() with options for true streaming
            #[cfg(feature = "native-inference")]
            RigProvider::Native(runtime) => {
                use futures::StreamExt;
                use std::pin::pin;

                // Native doesn't support preamble — concatenate system prompt for native only
                let native_prompt = if let Some(ref system) = options.system {
                    format!("{}\n\n{}", system, prompt)
                } else {
                    prompt.to_string()
                };
                let chat_options = super::native::ChatOptions {
                    temperature: options.temperature.map(|t| t as f32),
                    max_tokens: options.max_tokens,
                    ..Default::default()
                };
                let stream = runtime
                    .infer_stream(&native_prompt, chat_options)
                    .await
                    .map_err(|e: super::native::NativeError| {
                        RigInferError::PromptError(e.to_string())
                    })?;

                // Pin the stream for iteration (async_stream produces !Unpin streams)
                let mut stream = pin!(stream);

                // Collect tokens as they arrive (Stream yields Result<String, NativeError>)
                while let Some(result) = stream.next().await {
                    match result {
                        Ok(token) => {
                            response_parts.push(token.clone());
                            let _ = tx.try_send(StreamChunk::Token(token));
                        }
                        Err(e) => {
                            let _ = tx.try_send(StreamChunk::Error(e.to_string()));
                            return Err(RigInferError::PromptError(e.to_string()));
                        }
                    }
                }

                // Note: Token counts not available in streaming mode
                // They would require post-hoc tokenization
            }
        }

        let complete_response = response_parts.concat();
        let _ = tx.try_send(StreamChunk::Done(complete_response.clone()));

        let _ = tx.try_send(StreamChunk::Metrics {
            input_tokens: result.input_tokens,
            output_tokens: result.output_tokens,
        });

        result.text = complete_response;
        Ok(result)
    }
}

// =============================================================================
// NikaMcpTool - Wrapper for MCP tools implementing rig-core's ToolDyn
// =============================================================================

/// Tool definition for Nika MCP tools.
///
/// This is our own definition struct that avoids the rmcp version conflict.
/// We convert MCP tool definitions from rmcp 0.16 into this format.
#[derive(Debug, Clone)]
pub struct NikaMcpToolDef {
    /// Tool name (e.g., "novanet_context")
    pub name: String,
    /// Tool description for the LLM
    pub description: String,
    /// JSON Schema for input parameters
    pub input_schema: serde_json::Value,
}

/// Shared media staging for agent tool calls.
///
/// When agent tools return binary content (images, audio, etc.),
/// the content blocks are collected here since rig's `ToolDyn::call()`
/// can only return `String`. After the agent loop completes,
/// `run_agent()` drains this map and runs the MediaProcessor pipeline.
pub type AgentMediaStaging = Arc<dashmap::DashMap<String, Vec<crate::mcp::types::ContentBlock>>>;

/// MCP tool wrapper implementing rig-core's `ToolDyn` trait.
///
/// This allows us to use our MCP tools (rmcp 0.16) with rig-core's
/// agent system without version conflicts.
///
/// Binary content from tool results is staged via `media_staging`
/// side-channel since rig's `ToolDyn::call()` returns `String` only.
#[derive(Debug, Clone)]
pub struct NikaMcpTool {
    definition: NikaMcpToolDef,
    /// Optional MCP client for real tool calls
    client: Option<Arc<McpClient>>,
    /// Shared staging for binary content blocks (agent media side-channel)
    media_staging: Option<AgentMediaStaging>,
}

impl NikaMcpTool {
    /// Create a new NikaMcpTool from a definition (without client)
    pub fn new(definition: NikaMcpToolDef) -> Self {
        Self {
            definition,
            client: None,
            media_staging: None,
        }
    }

    /// Create a new NikaMcpTool with an MCP client for real tool calls
    pub fn with_client(definition: NikaMcpToolDef, client: Arc<McpClient>) -> Self {
        Self {
            definition,
            client: Some(client),
            media_staging: None,
        }
    }

    /// Create a new NikaMcpTool with media staging for agent loops
    pub fn with_media_staging(
        definition: NikaMcpToolDef,
        client: Arc<McpClient>,
        staging: AgentMediaStaging,
    ) -> Self {
        Self {
            definition,
            client: Some(client),
            media_staging: Some(staging),
        }
    }

    /// Get the tool name
    pub fn tool_name(&self) -> &str {
        &self.definition.name
    }
}

/// Type alias for boxed future (required by ToolDyn)
type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

impl ToolDyn for NikaMcpTool {
    fn name(&self) -> String {
        self.definition.name.clone()
    }

    fn definition(&self, _prompt: String) -> BoxFuture<'_, ToolDefinition> {
        let def = ToolDefinition {
            name: self.definition.name.clone(),
            description: self.definition.description.clone(),
            parameters: self.definition.input_schema.clone(),
        };
        Box::pin(async move { def })
    }

    fn call(&self, args: String) -> BoxFuture<'_, Result<String, ToolError>> {
        let tool_name = self.definition.name.clone();
        let client = self.client.clone();

        Box::pin(async move {
            // Parse the args as JSON
            let params: serde_json::Value = serde_json::from_str(&args).map_err(|e| {
                ToolError::ToolCallError(Box::new(McpToolError::invalid_args(format!(
                    "Invalid JSON arguments: {}",
                    e
                ))))
            })?;

            // Check if we have a client
            let client = client.ok_or_else(|| {
                ToolError::ToolCallError(Box::new(McpToolError::not_configured(
                    "No MCP client configured for this tool",
                )))
            })?;

            // Call the MCP tool
            let result = client.call_tool(&tool_name, params).await.map_err(|e| {
                ToolError::ToolCallError(Box::new(McpToolError::call_failed(format!(
                    "MCP tool call failed: {}",
                    e
                ))))
            })?;

            // Stage binary content blocks via side-channel (if media staging is enabled)
            if result.has_media() {
                if let Some(ref staging) = self.media_staging {
                    let media_blocks: Vec<_> = result.media_blocks().into_iter().cloned().collect();
                    if !media_blocks.is_empty() {
                        tracing::debug!(
                            tool = %tool_name,
                            media_count = media_blocks.len(),
                            "agent: staging binary content from tool call"
                        );
                        staging
                            .entry(tool_name.clone())
                            .or_default()
                            .extend(media_blocks);
                    }
                } else {
                    tracing::warn!(
                        tool = %tool_name,
                        media_count = result.media_blocks().len(),
                        "agent: tool returned binary content but no media staging configured — data will be lost"
                    );
                }
            }

            // Extract text content from the result
            let output = result.text();

            if output.is_empty() {
                // Return the full result as JSON if no text content
                serde_json::to_string(&result).map_err(|e| {
                    ToolError::ToolCallError(Box::new(McpToolError::serialization(format!(
                        "Failed to serialize result: {}",
                        e
                    ))))
                })
            } else {
                Ok(output)
            }
        })
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// NATIVE VISION HELPER
// ═══════════════════════════════════════════════════════════════════════════

/// Extract text prompt and `VisionImage` instances from rig `UserContent` parts.
///
/// The executor builds `Vec<UserContent>` with base64-encoded images for cloud providers.
/// For native inference, we need to decode the base64 back into raw bytes and produce
/// `VisionImage` instances that `NativeRuntime::infer_vision()` can consume.
///
/// # Returns
/// `(prompt_text, vision_images)` where prompt_text is all text parts joined by newlines.
#[cfg(feature = "native-inference")]
fn extract_native_vision_parts(
    user_content: &[rig::completion::message::UserContent],
) -> Result<(String, Vec<crate::core::backend::VisionImage>), RigInferError> {
    use base64::Engine as _;
    use rig::completion::message::{DocumentSourceKind, Image, UserContent};

    let mut text_parts: Vec<String> = Vec::new();
    let mut images: Vec<crate::core::backend::VisionImage> = Vec::new();

    for part in user_content {
        match part {
            UserContent::Text(text) => {
                text_parts.push(text.text.clone());
            }
            UserContent::Image(Image {
                data, media_type, ..
            }) => {
                let bytes = match data {
                    DocumentSourceKind::Base64(b64) => base64::engine::general_purpose::STANDARD
                        .decode(b64)
                        .map_err(|e| {
                            RigInferError::PromptError(format!(
                                "Failed to decode base64 image for native vision: {}",
                                e
                            ))
                        })?,
                    DocumentSourceKind::Raw(raw) => raw.clone(),
                    DocumentSourceKind::Url(url) => {
                        return Err(RigInferError::VisionNotSupported(format!(
                            "Native vision does not support URL images. Pre-fetch the image: {}",
                            url
                        )));
                    }
                    _ => {
                        return Err(RigInferError::PromptError(
                            "Unsupported image source kind for native vision".to_string(),
                        ));
                    }
                };

                // Map rig's ImageMediaType to MIME string
                let mime = media_type
                    .as_ref()
                    .map(|mt| match mt {
                        rig::completion::message::ImageMediaType::JPEG => "image/jpeg",
                        rig::completion::message::ImageMediaType::PNG => "image/png",
                        rig::completion::message::ImageMediaType::GIF => "image/gif",
                        rig::completion::message::ImageMediaType::WEBP => "image/webp",
                        _ => "image/png", // Default fallback
                    })
                    .unwrap_or("image/png");

                images.push(crate::core::backend::VisionImage::new(bytes, mime));
            }
            // Skip non-image/text content (tool results, audio, etc.)
            _ => {}
        }
    }

    Ok((text_parts.join("\n"), images))
}

#[cfg(test)]
mod tests {
    use super::*;
    use serial_test::serial;

    // =========================================================================
    // StreamResult tests
    // =========================================================================

    #[test]
    fn stream_result_from_text_has_zero_tokens() {
        let result = StreamResult::from_text("hello world");
        assert_eq!(result.text, "hello world");
        assert_eq!(result.input_tokens, 0);
        assert_eq!(result.output_tokens, 0);
        assert_eq!(result.total_tokens, 0);
        assert_eq!(result.cached_input_tokens, 0);
    }

    #[test]
    fn stream_result_default_is_empty() {
        let result = StreamResult::default();
        assert_eq!(result.text, "");
        assert_eq!(result.total_tokens, 0);
    }

    #[test]
    fn stream_result_with_tokens() {
        let result = StreamResult {
            text: "response".to_string(),
            input_tokens: 100,
            output_tokens: 50,
            total_tokens: 150,
            cached_input_tokens: 20,
        };
        assert_eq!(
            result.total_tokens,
            result.input_tokens + result.output_tokens
        );
        assert_eq!(result.cached_input_tokens, 20);
    }

    #[test]
    #[serial]
    fn test_rig_provider_claude_returns_claude_variant() {
        // This test verifies that RigProvider::claude() creates a Claude variant
        // It will fail initially because we need ANTHROPIC_API_KEY env var
        // In real code, we'll use from_env() which reads the API key

        // For now, we test the name() method which doesn't require API call
        std::env::set_var("ANTHROPIC_API_KEY", "test-key-for-unit-test");
        let provider = RigProvider::claude();

        assert_eq!(provider.name(), "claude");
        assert!(matches!(provider, RigProvider::Claude(_)));
    }

    #[test]
    #[serial]
    fn test_rig_provider_openai_returns_openai_variant() {
        std::env::set_var("OPENAI_API_KEY", "test-key-for-unit-test");
        let provider = RigProvider::openai();

        assert_eq!(provider.name(), "openai");
        assert!(matches!(provider, RigProvider::OpenAI(_)));
    }

    #[test]
    #[serial]
    fn test_rig_provider_default_model_claude() {
        std::env::set_var("ANTHROPIC_API_KEY", "test-key-for-unit-test");
        let provider = RigProvider::claude();

        // Using explicit model name instead of rig-core constant
        // rig-core's CLAUDE_3_5_SONNET is outdated
        assert_eq!(provider.default_model(), "claude-sonnet-4-6");
    }

    #[test]
    #[serial]
    fn test_rig_provider_default_model_openai() {
        std::env::set_var("OPENAI_API_KEY", "test-key-for-unit-test");
        let provider = RigProvider::openai();

        assert_eq!(provider.default_model(), openai::GPT_4O);
    }

    #[test]
    fn test_rig_infer_error_display() {
        let err = RigInferError::PromptError("Test error message".to_string());
        assert_eq!(err.to_string(), "Completion error: Test error message");
    }

    #[test]
    fn test_rig_infer_error_timeout_display() {
        // Test new Timeout variant
        let err = RigInferError::Timeout { duration_ms: 60000 };
        assert_eq!(
            err.to_string(),
            "Stream timeout: no chunk received for 60000ms"
        );
    }

    // =========================================================================
    // New Provider Tests
    // =========================================================================

    #[test]
    #[serial]
    fn test_rig_provider_mistral_returns_mistral_variant() {
        std::env::set_var("MISTRAL_API_KEY", "test-key-for-unit-test");
        let provider = RigProvider::mistral();

        assert_eq!(provider.name(), "mistral");
        assert!(matches!(provider, RigProvider::Mistral(_)));
    }

    #[test]
    #[serial]
    fn test_rig_provider_groq_returns_groq_variant() {
        std::env::set_var("GROQ_API_KEY", "test-key-for-unit-test");
        let provider = RigProvider::groq();

        assert_eq!(provider.name(), "groq");
        assert!(matches!(provider, RigProvider::Groq(_)));
    }

    #[test]
    #[serial]
    fn test_rig_provider_deepseek_returns_deepseek_variant() {
        std::env::set_var("DEEPSEEK_API_KEY", "test-key-for-unit-test");
        let provider = RigProvider::deepseek();

        assert_eq!(provider.name(), "deepseek");
        assert!(matches!(provider, RigProvider::DeepSeek(_)));
    }

    #[test]
    #[serial]
    fn test_rig_provider_default_models_v06() {
        // Test all new provider default models
        std::env::set_var("MISTRAL_API_KEY", "test");
        std::env::set_var("GROQ_API_KEY", "test");
        std::env::set_var("DEEPSEEK_API_KEY", "test");

        assert_eq!(
            RigProvider::mistral().default_model(),
            mistral::MISTRAL_LARGE
        );
        assert_eq!(
            RigProvider::groq().default_model(),
            "llama-3.3-70b-versatile"
        );
        assert_eq!(RigProvider::deepseek().default_model(), "deepseek-chat");
    }

    #[test]
    #[serial]
    fn test_rig_provider_auto_detects_claude() {
        // Clear other keys, set only Claude
        std::env::remove_var("OPENAI_API_KEY");
        std::env::remove_var("MISTRAL_API_KEY");
        std::env::remove_var("GROQ_API_KEY");
        std::env::remove_var("DEEPSEEK_API_KEY");
        std::env::set_var("ANTHROPIC_API_KEY", "test-key");

        let provider = RigProvider::auto();
        assert!(provider.is_some());
        assert_eq!(provider.unwrap().name(), "claude");
    }

    #[test]
    #[serial]
    fn test_rig_provider_auto_returns_none_when_no_keys() {
        // Clear all API keys - uses #[serial] for test isolation
        clear_all_provider_env_vars();

        let provider = RigProvider::auto();
        assert!(provider.is_none());
    }

    // =========================================================================
    // Provider Fallback Chain Tests
    // =========================================================================

    /// Helper to clear all provider env vars for testing fallback chain
    fn clear_all_provider_env_vars() {
        std::env::remove_var("ANTHROPIC_API_KEY");
        std::env::remove_var("OPENAI_API_KEY");
        std::env::remove_var("MISTRAL_API_KEY");
        std::env::remove_var("GROQ_API_KEY");
        std::env::remove_var("DEEPSEEK_API_KEY");
        std::env::remove_var("GEMINI_API_KEY");
    }

    #[test]
    #[serial]
    fn test_auto_fallback_to_openai() {
        // Given: Only OPENAI_API_KEY is set (Claude not available)
        clear_all_provider_env_vars();
        std::env::set_var("OPENAI_API_KEY", "test-key");

        // When: auto() is called
        let provider = RigProvider::auto();

        // Then: Should fall back to OpenAI
        assert!(provider.is_some());
        assert_eq!(provider.unwrap().name(), "openai");
    }

    #[test]
    #[serial]
    fn test_auto_fallback_to_mistral() {
        // Given: Only MISTRAL_API_KEY is set
        clear_all_provider_env_vars();
        std::env::set_var("MISTRAL_API_KEY", "test-key");

        // When: auto() is called
        let provider = RigProvider::auto();

        // Then: Should fall back to Mistral
        assert!(provider.is_some());
        assert_eq!(provider.unwrap().name(), "mistral");
    }

    #[test]
    #[serial]
    fn test_auto_fallback_to_groq() {
        // Given: Only GROQ_API_KEY is set
        clear_all_provider_env_vars();
        std::env::set_var("GROQ_API_KEY", "test-key");

        // When: auto() is called
        let provider = RigProvider::auto();

        // Then: Should fall back to Groq
        assert!(provider.is_some());
        assert_eq!(provider.unwrap().name(), "groq");
    }

    #[test]
    #[serial]
    fn test_auto_fallback_to_deepseek() {
        // Given: Only DEEPSEEK_API_KEY is set
        clear_all_provider_env_vars();
        std::env::set_var("DEEPSEEK_API_KEY", "test-key");

        // When: auto() is called
        let provider = RigProvider::auto();

        // Then: Should fall back to DeepSeek
        assert!(provider.is_some());
        assert_eq!(provider.unwrap().name(), "deepseek");
    }

    #[test]
    #[serial]
    fn test_auto_fallback_to_gemini() {
        // Given: Only GEMINI_API_KEY is set
        clear_all_provider_env_vars();
        std::env::set_var("GEMINI_API_KEY", "test-key");

        // When: auto() is called
        let provider = RigProvider::auto();

        // Then: Should fall back to Gemini
        assert!(provider.is_some());
        assert_eq!(provider.unwrap().name(), "gemini");
    }

    #[test]
    #[serial]
    fn test_auto_priority_claude_over_openai() {
        // Given: Both Claude and OpenAI keys are set
        clear_all_provider_env_vars();
        std::env::set_var("ANTHROPIC_API_KEY", "claude-key");
        std::env::set_var("OPENAI_API_KEY", "openai-key");

        // When: auto() is called
        let provider = RigProvider::auto();

        // Then: Should select Claude (higher priority)
        assert!(provider.is_some());
        assert_eq!(provider.unwrap().name(), "claude");
    }

    #[test]
    #[serial]
    fn test_auto_priority_openai_over_mistral() {
        // Given: OpenAI and Mistral keys are set (no Claude)
        clear_all_provider_env_vars();
        std::env::set_var("OPENAI_API_KEY", "openai-key");
        std::env::set_var("MISTRAL_API_KEY", "mistral-key");

        // When: auto() is called
        let provider = RigProvider::auto();

        // Then: Should select OpenAI (higher priority than Mistral)
        assert!(provider.is_some());
        assert_eq!(provider.unwrap().name(), "openai");
    }

    #[test]
    #[serial]
    fn test_auto_empty_env_var_treated_as_unset() {
        // Given: ANTHROPIC_API_KEY is set but empty
        clear_all_provider_env_vars();
        std::env::set_var("ANTHROPIC_API_KEY", ""); // Empty string
        std::env::set_var("OPENAI_API_KEY", "valid-key");

        // When: auto() is called
        let provider = RigProvider::auto();

        // Then: Should skip empty Claude and select OpenAI
        assert!(provider.is_some());
        assert_eq!(provider.unwrap().name(), "openai");
    }

    #[test]
    #[serial]
    fn test_auto_whitespace_env_var_treated_as_unset() {
        // Given: ANTHROPIC_API_KEY is set to whitespace only
        clear_all_provider_env_vars();
        std::env::set_var("ANTHROPIC_API_KEY", "   "); // Whitespace only

        // When: auto() is called
        let provider = RigProvider::auto();

        // Then: Should treat whitespace-only as unset
        // The implementation now uses !v.trim().is_empty() to reject whitespace-only keys
        assert!(
            provider.is_none(),
            "Whitespace-only API key should be treated as unset"
        );
    }

    // =========================================================================
    // NikaMcpTool tests
    // =========================================================================

    #[test]
    fn test_nika_mcp_tool_implements_tool_dyn() {
        // Given: A tool definition from our MCP infrastructure
        let tool_def = NikaMcpToolDef {
            name: "novanet_context".to_string(),
            description: "Generate native content for an entity".to_string(),
            input_schema: serde_json::json!({
                "type": "object",
                "properties": {
                    "entity": { "type": "string" },
                    "locale": { "type": "string" }
                },
                "required": ["entity", "locale"]
            }),
        };

        // When: We create a NikaMcpTool wrapper
        let tool = NikaMcpTool::new(tool_def);

        // Then: It should have the correct name
        assert_eq!(tool.tool_name(), "novanet_context");
    }

    #[test]
    fn test_nika_mcp_tool_definition_returns_correct_schema() {
        use rig::tool::ToolDyn;

        // Given: A NikaMcpTool with a specific schema
        let tool_def = NikaMcpToolDef {
            name: "novanet_describe".to_string(),
            description: "Describe an entity from the knowledge graph".to_string(),
            input_schema: serde_json::json!({
                "type": "object",
                "properties": {
                    "entity_key": { "type": "string" }
                },
                "required": ["entity_key"]
            }),
        };
        let tool = NikaMcpTool::new(tool_def);

        // When: We get the tool definition (sync wrapper for test)
        let name = tool.name();

        // Then: The definition should match
        assert_eq!(name, "novanet_describe");
    }

    // =========================================================================
    // RED: NikaMcpTool with McpClient - should FAIL until we wire up McpClient
    // =========================================================================

    #[tokio::test]
    async fn test_nika_mcp_tool_call_uses_mcp_client() {
        use crate::mcp::McpClient;
        use rig::tool::ToolDyn;
        use std::sync::Arc;

        // Given: A mock MCP client (pre-connected)
        let client = Arc::new(McpClient::mock("novanet"));

        // Given: A NikaMcpTool connected to the client
        let tool_def = NikaMcpToolDef {
            name: "novanet_describe".to_string(),
            description: "Describe an entity".to_string(),
            input_schema: serde_json::json!({
                "type": "object",
                "properties": {
                    "entity_key": { "type": "string" }
                },
                "required": ["entity_key"]
            }),
        };
        let tool = NikaMcpTool::with_client(tool_def, client);

        // When: We call the tool
        let args = r#"{"entity_key": "qr-code"}"#.to_string();
        let result = tool.call(args).await;

        // Then: The call should succeed (mock returns success)
        assert!(result.is_ok(), "Tool call should succeed with mock client");
        let output = result.unwrap();
        assert!(!output.is_empty(), "Tool should return non-empty output");
    }

    // =========================================================================
    // USE CASE TESTS - Real-world NovaNet MCP tool scenarios
    // =========================================================================

    /// UC1: novanet_context - Assemble LLM context for content generation
    #[tokio::test]
    async fn test_usecase_novanet_context_entity_locale() {
        use crate::mcp::McpClient;
        use rig::tool::ToolDyn;
        use std::sync::Arc;

        // Given: Mock NovaNet MCP client
        let client = Arc::new(McpClient::mock("novanet"));

        // Given: novanet_context tool with full schema (matching NovaNet MCP spec)
        let tool_def = NikaMcpToolDef {
            name: "novanet_context".to_string(),
            description: "Full RLM-on-KG context assembly for generation".to_string(),
            input_schema: serde_json::json!({
                "type": "object",
                "properties": {
                    "focus_key": { "type": "string", "description": "Entity key to generate for" },
                    "locale": { "type": "string", "description": "BCP-47 locale code" },
                    "mode": { "type": "string", "enum": ["block", "page"], "default": "block" },
                    "token_budget": { "type": "integer", "default": 4000 },
                    "spreading_depth": { "type": "integer", "default": 2 },
                    "forms": {
                        "type": "array",
                        "items": { "type": "string", "enum": ["text", "title", "abbrev", "url"] }
                    }
                },
                "required": ["focus_key", "locale"]
            }),
        };
        let tool = NikaMcpTool::with_client(tool_def, client);

        // When: Calling for QR code entity in French
        let args = serde_json::json!({
            "focus_key": "qr-code",
            "locale": "fr-FR",
            "mode": "page",
            "forms": ["text", "title", "abbrev"]
        })
        .to_string();

        let result = tool.call(args).await;

        // Then: Should succeed with mock response
        assert!(
            result.is_ok(),
            "novanet_context should succeed: {:?}",
            result
        );
        let output = result.unwrap();
        assert!(!output.is_empty(), "Should return generation context");
    }

    /// UC2: novanet_describe - Get entity details
    #[tokio::test]
    async fn test_usecase_novanet_describe_entity() {
        use crate::mcp::McpClient;
        use rig::tool::ToolDyn;
        use std::sync::Arc;

        let client = Arc::new(McpClient::mock("novanet"));

        let tool_def = NikaMcpToolDef {
            name: "novanet_describe".to_string(),
            description: "Bootstrap agent understanding of the knowledge graph".to_string(),
            input_schema: serde_json::json!({
                "type": "object",
                "properties": {
                    "describe": {
                        "type": "string",
                        "enum": ["schema", "entity", "category", "relations", "locales", "stats"]
                    },
                    "entity_key": { "type": "string" },
                    "category_key": { "type": "string" }
                },
                "required": ["describe"]
            }),
        };
        let tool = NikaMcpTool::with_client(tool_def, client);

        // When: Describing schema overview
        let args = serde_json::json!({
            "describe": "schema"
        })
        .to_string();

        let result = tool.call(args).await;
        assert!(result.is_ok(), "novanet_describe should succeed");
    }

    /// UC3: novanet_search (walk mode) - Graph traversal
    #[tokio::test]
    async fn test_usecase_novanet_search_walk_graph() {
        use crate::mcp::McpClient;
        use rig::tool::ToolDyn;
        use std::sync::Arc;

        let client = Arc::new(McpClient::mock("novanet"));

        let tool_def = NikaMcpToolDef {
            name: "novanet_search".to_string(),
            description: "Graph traversal with configurable depth and filters".to_string(),
            input_schema: serde_json::json!({
                "type": "object",
                "properties": {
                    "start_key": { "type": "string" },
                    "max_depth": { "type": "integer", "default": 2 },
                    "direction": { "type": "string", "enum": ["outgoing", "incoming", "both"] },
                    "arc_families": { "type": "array", "items": { "type": "string" } },
                    "target_kinds": { "type": "array", "items": { "type": "string" } }
                },
                "required": ["start_key"]
            }),
        };
        let tool = NikaMcpTool::with_client(tool_def, client);

        // When: Traversing from QR code with HAS_NATIVE arc
        let args = serde_json::json!({
            "start_key": "qr-code",
            "max_depth": 2,
            "direction": "outgoing",
            "arc_families": ["ownership", "localization"]
        })
        .to_string();

        let result = tool.call(args).await;
        assert!(result.is_ok(), "novanet_search walk should succeed");
    }

    /// UC4: novanet_search - Hybrid search
    #[tokio::test]
    async fn test_usecase_novanet_search_hybrid() {
        use crate::mcp::McpClient;
        use rig::tool::ToolDyn;
        use std::sync::Arc;

        let client = Arc::new(McpClient::mock("novanet"));

        let tool_def = NikaMcpToolDef {
            name: "novanet_search".to_string(),
            description: "Fulltext + property search with hybrid mode".to_string(),
            input_schema: serde_json::json!({
                "type": "object",
                "properties": {
                    "query": { "type": "string" },
                    "mode": { "type": "string", "enum": ["fulltext", "property", "hybrid"] },
                    "kinds": { "type": "array", "items": { "type": "string" } },
                    "realm": { "type": "string", "enum": ["shared", "org"] },
                    "limit": { "type": "integer", "default": 10 }
                },
                "required": ["query"]
            }),
        };
        let tool = NikaMcpTool::with_client(tool_def, client);

        // When: Searching for QR-related entities
        let args = serde_json::json!({
            "query": "QR code generator",
            "mode": "hybrid",
            "kinds": ["Entity", "Page"],
            "limit": 5
        })
        .to_string();

        let result = tool.call(args).await;
        assert!(result.is_ok(), "novanet_search should succeed");
    }

    /// UC5: novanet_audit - Quality checks with CSR metrics
    #[tokio::test]
    async fn test_usecase_novanet_audit_locale() {
        use crate::mcp::McpClient;
        use rig::tool::ToolDyn;
        use std::sync::Arc;

        let client = Arc::new(McpClient::mock("novanet"));

        let tool_def = NikaMcpToolDef {
            name: "novanet_audit".to_string(),
            description: "Retrieve knowledge atoms for a specific locale".to_string(),
            input_schema: serde_json::json!({
                "type": "object",
                "properties": {
                    "locale": { "type": "string" },
                    "atom_type": {
                        "type": "string",
                        "enum": ["term", "expression", "pattern", "cultureref", "taboo", "audiencetrait", "all"]
                    },
                    "domain": { "type": "string" }
                },
                "required": ["locale"]
            }),
        };
        let tool = NikaMcpTool::with_client(tool_def, client);

        // When: Getting French terms for QR codes
        let args = serde_json::json!({
            "locale": "fr-FR",
            "atom_type": "term",
            "domain": "qr-code"
        })
        .to_string();

        let result = tool.call(args).await;
        assert!(result.is_ok(), "novanet_audit should succeed");
    }

    /// UC6: novanet_batch - Parallel operations
    #[tokio::test]
    async fn test_usecase_novanet_batch_context() {
        use crate::mcp::McpClient;
        use rig::tool::ToolDyn;
        use std::sync::Arc;

        let client = Arc::new(McpClient::mock("novanet"));

        let tool_def = NikaMcpToolDef {
            name: "novanet_batch".to_string(),
            description: "Assemble context for LLM generation (token-aware)".to_string(),
            input_schema: serde_json::json!({
                "type": "object",
                "properties": {
                    "focus_key": { "type": "string" },
                    "locale": { "type": "string" },
                    "token_budget": { "type": "integer", "default": 4000 },
                    "strategy": {
                        "type": "string",
                        "enum": ["breadth", "depth", "relevance", "custom"]
                    }
                },
                "required": ["focus_key", "locale"]
            }),
        };
        let tool = NikaMcpTool::with_client(tool_def, client);

        // When: Assembling context for Spanish QR code generation
        let args = serde_json::json!({
            "focus_key": "qr-code",
            "locale": "es-MX",
            "token_budget": 3000,
            "strategy": "relevance"
        })
        .to_string();

        let result = tool.call(args).await;
        assert!(result.is_ok(), "novanet_batch should succeed");
    }

    // =========================================================================
    // ERROR HANDLING TESTS
    // =========================================================================

    /// Test that calling without client returns proper error
    #[tokio::test]
    async fn test_error_no_client_configured() {
        use rig::tool::ToolDyn;

        // Given: NikaMcpTool WITHOUT client
        let tool_def = NikaMcpToolDef {
            name: "novanet_describe".to_string(),
            description: "Test tool".to_string(),
            input_schema: serde_json::json!({"type": "object"}),
        };
        let tool = NikaMcpTool::new(tool_def); // No client!

        // When: Calling the tool
        let args = r#"{"entity_key": "test"}"#.to_string();
        let result = tool.call(args).await;

        // Then: Should fail with NotConnected error
        assert!(result.is_err(), "Should fail without client");
        let err = result.unwrap_err();
        let err_str = err.to_string();
        assert!(
            err_str.contains("No MCP client") || err_str.contains("NotConnected"),
            "Error should mention missing client: {}",
            err_str
        );
    }

    /// Test that invalid JSON arguments return proper error
    #[tokio::test]
    async fn test_error_invalid_json_arguments() {
        use crate::mcp::McpClient;
        use rig::tool::ToolDyn;
        use std::sync::Arc;

        let client = Arc::new(McpClient::mock("novanet"));
        let tool_def = NikaMcpToolDef {
            name: "novanet_describe".to_string(),
            description: "Test tool".to_string(),
            input_schema: serde_json::json!({"type": "object"}),
        };
        let tool = NikaMcpTool::with_client(tool_def, client);

        // When: Calling with invalid JSON
        let args = "not valid json {{{".to_string();
        let result = tool.call(args).await;

        // Then: Should fail with JSON parsing error
        assert!(result.is_err(), "Should fail with invalid JSON");
        let err = result.unwrap_err();
        let err_str = err.to_string();
        assert!(
            err_str.contains("Invalid JSON") || err_str.contains("JSON"),
            "Error should mention JSON parsing: {}",
            err_str
        );
    }

    /// Test that empty JSON object is valid
    #[tokio::test]
    async fn test_empty_json_object_is_valid() {
        use crate::mcp::McpClient;
        use rig::tool::ToolDyn;
        use std::sync::Arc;

        let client = Arc::new(McpClient::mock("novanet"));
        let tool_def = NikaMcpToolDef {
            name: "novanet_describe".to_string(),
            description: "Test tool".to_string(),
            input_schema: serde_json::json!({"type": "object"}),
        };
        let tool = NikaMcpTool::with_client(tool_def, client);

        // When: Calling with empty JSON object
        let args = "{}".to_string();
        let result = tool.call(args).await;

        // Then: Should succeed (empty args are valid)
        assert!(result.is_ok(), "Empty JSON object should be valid");
    }

    // =========================================================================
    // TOOL DEFINITION TESTS
    // =========================================================================

    /// Test async definition method returns correct schema
    #[tokio::test]
    async fn test_tool_definition_async() {
        use rig::tool::ToolDyn;

        let input_schema = serde_json::json!({
            "type": "object",
            "properties": {
                "entity_key": { "type": "string" },
                "locale": { "type": "string" }
            },
            "required": ["entity_key"]
        });

        let tool_def = NikaMcpToolDef {
            name: "test_tool".to_string(),
            description: "A test tool for verification".to_string(),
            input_schema: input_schema.clone(),
        };
        let tool = NikaMcpTool::new(tool_def);

        // When: Getting the tool definition
        let definition = tool.definition("some prompt".to_string()).await;

        // Then: Definition should match
        assert_eq!(definition.name, "test_tool");
        assert_eq!(definition.description, "A test tool for verification");
        assert_eq!(definition.parameters, input_schema);
    }

    /// Test multiple tools can coexist
    #[test]
    fn test_multiple_tools_independent() {
        // Given: Multiple tool definitions
        let tool1 = NikaMcpTool::new(NikaMcpToolDef {
            name: "novanet_context".to_string(),
            description: "Generate content".to_string(),
            input_schema: serde_json::json!({"type": "object"}),
        });

        let tool2 = NikaMcpTool::new(NikaMcpToolDef {
            name: "novanet_describe".to_string(),
            description: "Describe entity".to_string(),
            input_schema: serde_json::json!({"type": "object"}),
        });

        let tool3 = NikaMcpTool::new(NikaMcpToolDef {
            name: "novanet_search".to_string(),
            description: "Traverse graph".to_string(),
            input_schema: serde_json::json!({"type": "object"}),
        });

        // Then: Each tool maintains its own identity
        assert_eq!(tool1.tool_name(), "novanet_context");
        assert_eq!(tool2.tool_name(), "novanet_describe");
        assert_eq!(tool3.tool_name(), "novanet_search");
    }

    /// Test tool can be cloned and remains functional
    #[tokio::test]
    async fn test_tool_clone_works() {
        use crate::mcp::McpClient;
        use rig::tool::ToolDyn;
        use std::sync::Arc;

        let client = Arc::new(McpClient::mock("novanet"));
        let tool_def = NikaMcpToolDef {
            name: "novanet_describe".to_string(),
            description: "Test tool".to_string(),
            input_schema: serde_json::json!({"type": "object"}),
        };
        let tool = NikaMcpTool::with_client(tool_def, client);

        // When: Cloning the tool
        let cloned_tool = tool.clone();

        // Then: Both should work independently
        let args = r#"{"entity_key": "test"}"#.to_string();
        let result1 = tool.call(args.clone()).await;
        let result2 = cloned_tool.call(args).await;

        assert!(result1.is_ok(), "Original tool should work");
        assert!(result2.is_ok(), "Cloned tool should work");
    }

    // =========================================================================
    // MULTI-LOCALE TESTS (Real-world scenarios)
    // =========================================================================

    /// Test generating for multiple locales (common Nika workflow pattern)
    #[tokio::test]
    async fn test_multi_locale_generation_workflow() {
        use crate::mcp::McpClient;
        use rig::tool::ToolDyn;
        use std::sync::Arc;

        let client = Arc::new(McpClient::mock("novanet"));
        let tool_def = NikaMcpToolDef {
            name: "novanet_context".to_string(),
            description: "Generate native content".to_string(),
            input_schema: serde_json::json!({
                "type": "object",
                "properties": {
                    "focus_key": { "type": "string" },
                    "locale": { "type": "string" },
                    "forms": { "type": "array", "items": { "type": "string" } }
                },
                "required": ["focus_key", "locale"]
            }),
        };
        let tool = NikaMcpTool::with_client(tool_def, client);

        // When: Generating for multiple locales (simulating for_each workflow)
        let locales = ["fr-FR", "es-MX", "de-DE", "ja-JP", "zh-CN"];
        let mut results = Vec::new();

        for locale in locales {
            let args = serde_json::json!({
                "focus_key": "qr-code",
                "locale": locale,
                "forms": ["text", "title"]
            })
            .to_string();

            let result = tool.call(args).await;
            results.push((locale, result.is_ok()));
        }

        // Then: All locales should succeed
        for (locale, success) in &results {
            assert!(success, "Generation for {} should succeed", locale);
        }
        assert_eq!(results.len(), 5, "Should process all 5 locales");
    }

    // =========================================================================
    // Provider Verification Tests
    // =========================================================================

    #[test]
    fn test_provider_verify_error_types() {
        // Test all error variants
        let invalid_key = ProviderVerifyError::InvalidApiKey {
            provider: "claude".to_string(),
        };
        assert!(invalid_key.to_string().contains("Invalid API key"));
        assert!(invalid_key.suggestion().contains("API key"));

        let rate_limited = ProviderVerifyError::RateLimited {
            provider: "openai".to_string(),
        };
        assert!(rate_limited.to_string().contains("Rate limited"));

        let timeout = ProviderVerifyError::Timeout {
            provider: "mistral".to_string(),
        };
        assert!(timeout.to_string().contains("timeout"));

        let network = ProviderVerifyError::NetworkError {
            provider: "groq".to_string(),
            details: "connection refused".to_string(),
        };
        assert!(network.to_string().contains("Network error"));

        let provider_err = ProviderVerifyError::ProviderError {
            provider: "deepseek".to_string(),
            details: "server down".to_string(),
        };
        assert!(provider_err.to_string().contains("server down"));
    }

    #[test]
    fn test_provider_verify_result_fields() {
        let result = ProviderVerifyResult {
            provider: "claude".to_string(),
            latency: std::time::Duration::from_millis(150),
            model: "claude-sonnet-4-6".to_string(),
        };

        assert_eq!(result.provider, "claude");
        assert_eq!(result.latency.as_millis(), 150);
        assert_eq!(result.model, "claude-sonnet-4-6");
    }

    #[test]
    #[serial]
    fn test_is_configured_with_api_key() {
        std::env::set_var("ANTHROPIC_API_KEY", "test-key");
        let provider = RigProvider::claude();
        assert!(provider.is_configured());
    }

    #[test]
    #[serial]
    fn test_is_configured_returns_true_for_all_providers_with_keys() {
        // Set up all API keys
        std::env::set_var("ANTHROPIC_API_KEY", "test");
        std::env::set_var("OPENAI_API_KEY", "test");
        std::env::set_var("MISTRAL_API_KEY", "test");
        std::env::set_var("GROQ_API_KEY", "test");
        std::env::set_var("DEEPSEEK_API_KEY", "test");

        assert!(RigProvider::claude().is_configured());
        assert!(RigProvider::openai().is_configured());
        assert!(RigProvider::mistral().is_configured());
        assert!(RigProvider::groq().is_configured());
        assert!(RigProvider::deepseek().is_configured());
    }

    // =========================================================================
    // InferOptions Tests
    // =========================================================================

    #[test]
    fn test_infer_options_default() {
        let opts = InferOptions::default();
        assert!(opts.model.is_none());
        assert!(opts.temperature.is_none());
        assert!(opts.max_tokens.is_none());
        assert!(opts.system.is_none());
    }

    #[test]
    fn test_infer_options_with_all_fields() {
        let opts = InferOptions {
            model: Some("gpt-4o".to_string()),
            temperature: Some(0.7),
            max_tokens: Some(2000),
            system: Some("You are a helpful assistant.".to_string()),
        };
        assert_eq!(opts.model.as_deref(), Some("gpt-4o"));
        assert_eq!(opts.temperature, Some(0.7));
        assert_eq!(opts.max_tokens, Some(2000));
        assert_eq!(opts.system.as_deref(), Some("You are a helpful assistant."));
    }

    #[test]
    fn test_infer_options_partial_fields() {
        let opts = InferOptions {
            temperature: Some(0.5),
            ..Default::default()
        };
        assert!(opts.model.is_none());
        assert_eq!(opts.temperature, Some(0.5));
        assert!(opts.max_tokens.is_none());
        assert!(opts.system.is_none());
    }

    #[test]
    fn test_infer_options_temperature_zero() {
        let opts = InferOptions {
            temperature: Some(0.0),
            ..Default::default()
        };
        assert_eq!(opts.temperature, Some(0.0));
    }

    #[test]
    fn test_infer_options_max_tokens_small() {
        let opts = InferOptions {
            max_tokens: Some(1),
            ..Default::default()
        };
        assert_eq!(opts.max_tokens, Some(1));
    }

    #[test]
    fn test_infer_options_system_empty_string() {
        let opts = InferOptions {
            system: Some(String::new()),
            ..Default::default()
        };
        assert_eq!(opts.system.as_deref(), Some(""));
    }

    #[test]
    fn test_infer_options_clone() {
        let opts = InferOptions {
            model: Some("test-model".to_string()),
            temperature: Some(0.8),
            max_tokens: Some(1000),
            system: Some("Test system".to_string()),
        };
        let cloned = opts.clone();
        assert_eq!(opts.model, cloned.model);
        assert_eq!(opts.temperature, cloned.temperature);
        assert_eq!(opts.max_tokens, cloned.max_tokens);
        assert_eq!(opts.system, cloned.system);
    }

    // =========================================================================
    // Vision Provider Tests
    // =========================================================================

    #[test]
    fn vision_not_supported_error_display() {
        let err = RigInferError::VisionNotSupported("DeepSeek no vision".to_string());
        assert!(err.to_string().contains("Vision not supported"));
        assert!(err.to_string().contains("DeepSeek no vision"));
    }

    /// Test DeepSeek vision rejection (only when DEEPSEEK_API_KEY is set)
    #[tokio::test]
    async fn infer_vision_deepseek_returns_error() {
        if std::env::var("DEEPSEEK_API_KEY").is_err() {
            // Can't construct DeepSeek without API key; test message building instead
            let err = RigInferError::VisionNotSupported("DeepSeek".to_string());
            assert!(err.to_string().contains("Vision not supported"));
            return;
        }
        let provider = RigProvider::deepseek();
        let content = vec![rig::completion::message::UserContent::text("hello")];
        let result = provider.infer_vision(content, None, None, None).await;
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            RigInferError::VisionNotSupported(_)
        ));
    }

    #[test]
    fn infer_vision_empty_content_builds_error() {
        // OneOrMany::many rejects empty vecs, which infer_vision maps to VisionNotSupported
        use rig::OneOrMany;
        let content: Vec<rig::completion::message::UserContent> = vec![];
        let result = OneOrMany::many(content);
        assert!(result.is_err(), "empty content should fail");
    }

    #[test]
    fn build_vision_user_content_text_only() {
        let content = [rig::completion::message::UserContent::text("Describe this")];
        assert_eq!(content.len(), 1);
    }

    #[test]
    fn build_vision_user_content_with_image() {
        use rig::completion::message::{ImageMediaType, UserContent};
        let content = [
            UserContent::text("What is in this image?"),
            UserContent::image_base64(
                "iVBORw0KGgo=", // fake base64
                Some(ImageMediaType::PNG),
                None,
            ),
        ];
        assert_eq!(content.len(), 2);
    }

    #[test]
    fn build_vision_message_from_content() {
        use rig::completion::message::{ImageMediaType, Message, UserContent};
        use rig::OneOrMany;

        let parts = vec![
            UserContent::text("Describe this image"),
            UserContent::image_base64("iVBORw0KGgo=", Some(ImageMediaType::PNG), None),
        ];
        let msg = Message::User {
            content: OneOrMany::many(parts).unwrap(),
        };
        assert!(matches!(msg, Message::User { .. }));
    }
}