riglr-core 0.3.0

Core abstractions and job execution engine for riglr - building resilient AI agents.
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
//! Tool orchestration and execution framework.
//!
//! Provides the ToolWorker abstraction for coordinating tool execution
//! with proper error handling, logging, and integration with rig agents.
//!
//! This module provides the core abstractions for executing tools in a resilient,
//! asynchronous manner with support for retries, timeouts, and job queuing.
//!
//! ## Overview
//!
//! The tool execution system is designed around several key components:
//!
//! - **[`Tool`]** - The core trait defining executable tools
//! - **[`ToolWorker`]** - The execution engine that processes jobs using registered tools
//! - **[`ExecutionConfig`]** - Configuration for retry behavior, timeouts, and resource limits
//! - **[`ResourceLimits`]** - Fine-grained control over resource usage per tool type
//! - **[`WorkerMetrics`]** - Performance and operational metrics for monitoring
//!
//! ## Key Features
//!
//! ### Resilient Execution
//! - **Exponential backoff** retry logic with configurable delays
//! - **Timeout protection** to prevent hanging operations
//! - **Error classification** to distinguish retriable vs permanent failures
//! - **Idempotency support** to safely retry operations
//!
//! ### Resource Management
//! - **Semaphore-based limits** for different resource types (RPC calls, HTTP requests)
//! - **Concurrent execution** with configurable limits per resource
//! - **Tool-specific resource mapping** based on naming patterns
//!
//! ### Monitoring and Observability
//! - **Comprehensive metrics** tracking success/failure rates
//! - **Structured logging** with correlation IDs
//! - **Performance monitoring** with execution timings
//!
//! ## Examples
//!
//! ### Basic Tool Implementation
//!
//! ```ignore
//! use riglr_core::{Tool, JobResult};
//! use async_trait::async_trait;
//! use serde_json::Value;
//!
//! struct SimpleCalculator;
//!
//! #[async_trait]
//! impl Tool for SimpleCalculator {
//!     async fn execute(&self, params: Value, _context: &ApplicationContext) -> Result<JobResult, ToolError> {
//!         let a = params["a"].as_f64().ok_or("Missing parameter 'a'")?;
//!         let b = params["b"].as_f64().ok_or("Missing parameter 'b'")?;
//!         let operation = params["op"].as_str().unwrap_or("add");
//!
//!         let result = match operation {
//!             "add" => a + b,
//!             "multiply" => a * b,
//!             "divide" => {
//!                 if b == 0.0 {
//!                     return Err(ToolError::permanent_string("Division by zero", "Cannot divide by zero"));
//!                 }
//!                 a / b
//!             }
//!             _ => return Err(ToolError::permanent_string("Unknown operation", "Operation not supported")),
//!         };
//!
//!         Ok(JobResult::success(&result)?)
//!     }
//!
//!     fn name(&self) -> &str {
//!         "calculator"
//!     }
//! }
//! ```
//!
//! ### Worker Setup and Execution
//!
//! ```ignore
//! use riglr_core::{
//!     ToolWorker, ExecutionConfig, ResourceLimits, Job,
//!     idempotency::InMemoryIdempotencyStore
//! };
//! use std::{sync::Arc, time::Duration};
//!
//! # async fn example() -> anyhow::Result<()> {
//! // Configure execution behavior
//! let config = ExecutionConfig {
//!     max_concurrency: 20,
//!     default_timeout: Duration::from_secs(60),
//!     max_retries: 3,
//!     initial_retry_delay: Duration::from_millis(100),
//!     max_retry_delay: Duration::from_secs(30),
//!     enable_idempotency: true,
//!     ..Default::default()
//! };
//!
//! // Set up resource limits
//! let limits = ResourceLimits::default()
//!     .with_limit("solana_rpc", 5)   // Limit Solana RPC calls
//!     .with_limit("evm_rpc", 10)     // Limit EVM RPC calls
//!     .with_limit("http_api", 20);   // Limit HTTP API calls
//!
//! // Create worker with idempotency store
//! let store = Arc::new(InMemoryIdempotencyStore::new());
//! let worker = ToolWorker::new(config)
//!     .with_idempotency_store(store)
//!     .with_resource_limits(limits);
//!
//! // Register tools
//! # use riglr_core::{Tool, JobResult};
//! # use async_trait::async_trait;
//! # struct SimpleCalculator;
//! # #[async_trait]
//! # impl Tool for SimpleCalculator {
//! #     async fn execute(&self, _: serde_json::Value, _: &crate::provider::ApplicationContext) -> Result<JobResult, ToolError> {
//! #         Ok(JobResult::success(&42)?)
//! #     }
//! #     fn name(&self) -> &str { "calculator" }
//! # }
//! worker.register_tool(Arc::new(SimpleCalculator)).await;
//!
//! // Process a job
//! let job = Job::new_idempotent(
//!     "calculator",
//!     &serde_json::json!({"a": 10, "b": 5, "op": "add"}),
//!     3, // max retries
//!     "calc_10_plus_5" // idempotency key
//! )?;
//!
//! let result = worker.process_job(job).await.unwrap();
//! println!("Result: {:?}", result);
//!
//! // Get metrics
//! let metrics = worker.metrics();
//! println!("Jobs processed: {}", metrics.jobs_processed.load(std::sync::atomic::Ordering::Relaxed));
//! # Ok(())
//! # }
//! ```

use async_trait::async_trait;
use dashmap::DashMap;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use tracing::{debug, error, info, warn};

use crate::error::{ToolError, WorkerError};
use crate::idempotency::IdempotencyStore;
use crate::jobs::{Job, JobResult};
use crate::queue::JobQueue;
use crate::signer::SignerContext;

/// A trait defining the execution interface for tools.
///
/// This is compatible with `rig::Tool` and provides the foundation
/// for executing tools within the riglr ecosystem. Tools represent
/// individual operations that can be executed by the [`ToolWorker`].
///
/// ## Design Principles
///
/// - **Stateless**: Tools should not maintain internal state between executions
/// - **Idempotent**: When possible, tools should be safe to retry
/// - **Error-aware**: Tools should classify errors as retriable or permanent
/// - **Resource-conscious**: Tools should handle rate limits and timeouts gracefully
///
/// ## Error Handling
///
/// Tools should carefully distinguish between different types of errors:
///
/// - **Retriable errors**: Network timeouts, rate limits, temporary service unavailability
/// - **Permanent errors**: Invalid parameters, insufficient funds, authorization failures
/// - **System errors**: Internal configuration issues, unexpected state
///
/// ## Examples
///
/// ### Basic Tool Implementation
///
/// ```ignore
/// use riglr_core::{Tool, JobResult};
/// use async_trait::async_trait;
/// use serde_json::Value;
///
/// struct HttpFetcher;
///
/// #[async_trait]
/// impl Tool for HttpFetcher {
///     async fn execute(&self, params: Value, _context: &ApplicationContext) -> Result<JobResult, ToolError> {
///         let url = params["url"].as_str()
///             .ok_or("Missing required parameter: url")?;
///
///         // Mock HTTP client behavior for this example
///         if url.starts_with("https://") {
///             let body = r#"{"data": "success"}"#;
///             Ok(JobResult::success(&serde_json::json!({"body": body}))?)
///         } else if url.contains("error") {
///             // Simulate client error
///             Ok(JobResult::Failure {
///                 error: ToolError::permanent_string("Client error: Invalid URL")
///             })
///         } else if url.contains("timeout") {
///             // Simulate timeout
///             Ok(JobResult::Failure {
///                 error: ToolError::retriable_string("Request timeout: Connection timed out")
///             })
///         } else {
///             // Simulate server error
///             Ok(JobResult::Failure {
///                 error: ToolError::retriable_string("Server error: HTTP 503")
///             })
///         }
///     }
///
///     fn name(&self) -> &str {
///         "http_fetcher"
///     }
/// }
/// ```
///
/// ### Tool with Resource-Aware Naming
///
/// ```ignore
/// use riglr_core::{Tool, JobResult};
/// use async_trait::async_trait;
/// use serde_json::Value;
///
/// // The name starts with "solana_" which will use the solana_rpc resource limit
/// struct SolanaBalanceChecker;
///
/// #[async_trait]
/// impl Tool for SolanaBalanceChecker {
///     async fn execute(&self, params: Value, _context: &ApplicationContext) -> Result<JobResult, ToolError> {
///         let address = params["address"].as_str()
///             .ok_or("Missing required parameter: address")?;
///
///         // This tool will be rate-limited by the "solana_rpc" resource limit
///         // because its name starts with "solana_"
///
///         // Implementation would use Solana RPC client here...
///         let balance = 1.5; // Mock balance
///
///         Ok(JobResult::success(&serde_json::json!({
///             "address": address,
///             "balance": balance,
///             "unit": "SOL"
///         }))?)
///     }
///
///     fn name(&self) -> &str {
///         "solana_balance_check"  // Name prefix determines resource pool
///     }
/// }
/// ```
///
/// ### Tool Using Signer Context
///
/// ```ignore
/// use riglr_core::{Tool, JobResult, SignerContext};
/// use async_trait::async_trait;
/// use serde_json::Value;
///
/// struct TransferTool;
///
/// #[async_trait]
/// impl Tool for TransferTool {
///     async fn execute(&self, params: Value, _context: &ApplicationContext) -> Result<JobResult, ToolError> {
///         // Check if we have a signer context
///         if !SignerContext::is_available().await {
///             return Ok(JobResult::Failure {
///                 error: ToolError::permanent_string("Transfer operations require a signer context")
///             });
///         }
///
///         let signer = SignerContext::current().await
///             .map_err(|_| "Failed to get signer context")?;
///
///         let recipient = params["recipient"].as_str()
///             .ok_or("Missing required parameter: recipient")?;
///         let amount = params["amount"].as_f64()
///             .ok_or("Missing required parameter: amount")?;
///
///         // Use the signer to perform the transfer...
///         // This is just a mock implementation
///         Ok(JobResult::success_with_tx(
///             &serde_json::json!({
///                 "recipient": recipient,
///                 "amount": amount,
///                 "status": "completed"
///             }),
///             "mock_tx_hash_12345"
///         )?)
///     }
///
///     fn name(&self) -> &str {
///         "transfer"
///     }
/// }
/// ```
#[async_trait]
pub trait Tool: Send + Sync {
    /// Execute the tool with the given parameters.
    ///
    /// This method performs the core work of the tool. It receives parameters
    /// as a JSON value and should return a [`JobResult`] indicating success or failure.
    ///
    /// # Parameters
    /// * `params` - JSON parameters passed to the tool. Tools should validate
    ///              and extract required parameters, returning appropriate errors
    ///              for missing or invalid data.
    ///
    /// # Returns
    /// * `Ok(JobResult::Success)` - Tool executed successfully with result data
    /// * `Ok(JobResult::Failure { retriable: true })` - Tool failed but can be retried
    /// * `Ok(JobResult::Failure { retriable: false })` - Tool failed permanently
    /// * `Err(Box<dyn Error>)` - Unexpected system error occurred
    ///
    /// # Error Classification Guidelines
    ///
    /// Return retriable failures (`JobResult::Failure { error: ToolError::retriable_string(...) }`) for:
    /// - Network timeouts or connection errors
    /// - Rate limiting (HTTP 429, RPC rate limits) - use `ToolError::rate_limited_string` for these
    /// - Temporary service unavailability (HTTP 503)
    /// - Blockchain congestion or temporary RPC failures
    ///
    /// Return permanent failures (`JobResult::Failure { error: ToolError::permanent_string(...) }`) for:
    /// - Invalid parameters or malformed requests - use `ToolError::invalid_input_string` for these
    /// - Authentication/authorization failures
    /// - Insufficient funds or balance
    /// - Invalid blockchain addresses or transaction data
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use riglr_core::{Tool, JobResult};
    /// use async_trait::async_trait;
    /// use serde_json::Value;
    ///
    /// struct WeatherTool;
    ///
    /// #[async_trait]
    /// impl Tool for WeatherTool {
    ///     async fn execute(&self, params: Value, _context: &ApplicationContext) -> Result<JobResult, ToolError> {
    ///         // Validate parameters
    ///         let city = params["city"].as_str()
    ///             .ok_or("Missing required parameter: city")?;
    ///
    ///         if city.is_empty() {
    ///             return Ok(JobResult::Failure {
    ///                 error: ToolError::invalid_input_string("City name cannot be empty")
    ///             });
    ///         }
    ///
    ///         // Simulate API call with mock weather service
    ///         let weather_data = if city == "InvalidCity" {
    ///             return Ok(JobResult::Failure {
    ///                 error: ToolError::permanent_string(format!("City not found: {}", city))
    ///             });
    ///         } else if city == "TimeoutCity" {
    ///             return Ok(JobResult::Failure {
    ///                 error: ToolError::retriable_string("Network timeout")
    ///             });
    ///         } else {
    ///             serde_json::json!({
    ///                 "city": city,
    ///                 "temperature": 22,
    ///                 "condition": "sunny"
    ///             })
    ///         };
    ///
    ///         Ok(JobResult::success(&weather_data)?)
    ///     }
    ///
    ///     fn name(&self) -> &str {
    ///         "weather"
    ///     }
    /// }
    /// ```
    async fn execute(
        &self,
        params: serde_json::Value,
        context: &crate::provider::ApplicationContext,
    ) -> Result<JobResult, ToolError>;

    /// Get the name of this tool.
    ///
    /// The tool name is used for:
    /// - Tool registration and lookup in the worker
    /// - Job identification and logging
    /// - Resource limit mapping (based on name prefixes)
    /// - Metrics and monitoring
    ///
    /// # Naming Conventions
    ///
    /// Tool names should follow these patterns for automatic resource management:
    ///
    /// - `solana_*` - Uses "solana_rpc" resource pool (e.g., "solana_balance", "solana_transfer")
    /// - `evm_*` - Uses "evm_rpc" resource pool (e.g., "evm_balance", "evm_swap")
    /// - `web_*` - Uses "http_api" resource pool (e.g., "web_fetch", "web_scrape")
    /// - Others - Use default resource pool
    ///
    /// # Returns
    /// A string identifier for this tool that must be unique within a worker.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use riglr_core::Tool;
    /// # use async_trait::async_trait;
    /// # use riglr_core::JobResult;
    ///
    /// struct BitcoinPriceChecker;
    ///
    /// # #[async_trait]
    /// # impl Tool for BitcoinPriceChecker {
    /// #     async fn execute(&self, _: serde_json::Value, _: &crate::provider::ApplicationContext) -> Result<JobResult, ToolError> {
    /// #         Ok(JobResult::success(&42)?)
    /// #     }
    /// #
    /// fn name(&self) -> &str {
    ///     "web_bitcoin_price"  // Will use "http_api" resource pool
    /// }
    /// # }
    /// ```
    fn name(&self) -> &str;

    /// A concise, AI-friendly description of this tool's purpose.
    ///
    /// This should be a short, human-readable sentence that explains
    /// what the tool does and when to use it. It's intended for AI models
    /// and end-user UIs, and is separate from developer-facing rustdoc.
    ///
    /// When using the `#[tool]` macro from `riglr-macros`, this value is:
    /// - Taken from the explicit `#[tool(description = "...")]` attribute when provided
    /// - Otherwise derived from the item's doc comments
    /// - Falls back to an empty string if neither is present
    fn description(&self) -> &str;

    /// Returns the JSON schema for this tool's parameters.
    ///
    /// This schema is used by AI models to understand what parameters
    /// the tool accepts and their types. It should be a valid JSON Schema
    /// object describing the parameters structure.
    ///
    /// The default implementation returns a generic object schema that
    /// accepts any properties, which may not work well with all AI providers.
    /// Tools should override this to provide their actual parameter schema.
    fn schema(&self) -> serde_json::Value {
        // Default to a generic object schema
        serde_json::json!({
            "type": "object",
            "additionalProperties": true
        })
    }
}

/// Configuration for tool execution behavior.
///
/// This struct controls all aspects of how tools are executed by the [`ToolWorker`],
/// including retry behavior, timeouts, concurrency limits, and idempotency settings.
///
/// # Examples
///
/// ```ignore
/// use riglr_core::ExecutionConfig;
/// use std::time::Duration;
///
/// // Default configuration
/// let config = ExecutionConfig::default();
///
/// // Custom configuration for high-throughput scenario
/// let high_throughput_config = ExecutionConfig {
///     max_concurrency: 50,
///     default_timeout: Duration::from_secs(120),
///     max_retries: 5,
///     initial_retry_delay: Duration::from_millis(200),
///     max_retry_delay: Duration::from_secs(60),
///     enable_idempotency: true,
///     ..Default::default()
/// };
///
/// // Conservative configuration for sensitive operations
/// let conservative_config = ExecutionConfig {
///     max_concurrency: 5,
///     default_timeout: Duration::from_secs(300),
///     max_retries: 1,
///     initial_retry_delay: Duration::from_secs(5),
///     max_retry_delay: Duration::from_secs(30),
///     enable_idempotency: true,
///     ..Default::default()
/// };
/// ```
#[derive(Debug, Clone)]
pub struct ExecutionConfig {
    /// Maximum number of concurrent executions per resource type.
    ///
    /// This controls the default concurrency limit when no specific resource
    /// limit is configured. Individual resource types can have their own
    /// limits configured via [`ResourceLimits`].
    ///
    /// **Default**: 10
    pub max_concurrency: usize,

    /// Default timeout for tool execution.
    ///
    /// Individual tool executions will be cancelled if they exceed this duration.
    /// Tools should be designed to complete within reasonable time bounds.
    ///
    /// **Default**: 30 seconds
    pub default_timeout: Duration,

    /// Maximum number of retry attempts for failed operations.
    ///
    /// This applies only to retriable failures. Permanent failures are never retried.
    /// The total number of execution attempts will be `max_retries + 1`.
    ///
    /// **Default**: 3 retries (4 total attempts)
    pub max_retries: u32,

    /// Initial retry delay for exponential backoff.
    ///
    /// The first retry will wait this long after the initial failure.
    /// Subsequent retries will use exponentially increasing delays.
    ///
    /// **Default**: 100 milliseconds
    pub initial_retry_delay: Duration,

    /// Maximum retry delay for exponential backoff.
    ///
    /// Retry delays will not exceed this value, even with exponential backoff.
    /// This prevents excessive wait times for highly retried operations.
    ///
    /// **Default**: 10 seconds
    pub max_retry_delay: Duration,

    /// TTL for idempotency cache entries.
    ///
    /// Completed operations with idempotency keys will be cached for this duration.
    /// Subsequent requests with the same key will return the cached result.
    ///
    /// **Default**: 1 hour
    pub idempotency_ttl: Duration,

    /// Whether to enable idempotency checking.
    ///
    /// When enabled, jobs with idempotency keys will have their results cached
    /// and subsequent identical requests will return cached results instead of
    /// re-executing the tool.
    ///
    /// **Default**: true
    pub enable_idempotency: bool,
}

impl Default for ExecutionConfig {
    fn default() -> Self {
        Self {
            max_concurrency: 10,
            default_timeout: Duration::from_secs(30),
            max_retries: 3,
            initial_retry_delay: Duration::from_millis(100),
            max_retry_delay: Duration::from_secs(10),
            idempotency_ttl: Duration::from_secs(3600), // 1 hour
            enable_idempotency: true,
        }
    }
}

/// Resource limits configuration for fine-grained concurrency control.
///
/// This struct allows you to set different concurrency limits for different
/// types of operations, preventing any single resource type from overwhelming
/// external services or consuming too many system resources.
///
/// Resource limits are applied based on tool name prefixes:
/// - Tools starting with `solana_` use the "solana_rpc" resource pool
/// - Tools starting with `evm_` use the "evm_rpc" resource pool
/// - Tools starting with `web_` use the "http_api" resource pool
/// - All other tools use the default concurrency limit
///
/// # Examples
///
/// ```rust
/// use riglr_core::ResourceLimits;
///
/// // Create limits for different resource types
/// let limits = ResourceLimits::default()
///     .with_limit("solana_rpc", 3)     // Max 3 concurrent Solana RPC calls
///     .with_limit("evm_rpc", 8)        // Max 8 concurrent EVM RPC calls
///     .with_limit("http_api", 15)      // Max 15 concurrent HTTP requests
///     .with_limit("database", 5);      // Max 5 concurrent database operations
///
/// // Use default limits (solana_rpc: 5, evm_rpc: 10, http_api: 20)
/// let default_limits = ResourceLimits::default();
/// ```
///
/// # Resource Pool Mapping
///
/// The system automatically maps tool names to resource pools:
///
/// ```text
/// Tool Name              → Resource Pool    → Limit
/// "solana_balance"       → "solana_rpc"     → configured limit
/// "evm_swap"             → "evm_rpc"        → configured limit
/// "web_fetch"            → "http_api"       → configured limit
/// "custom_tool"          → default          → ExecutionConfig.max_concurrency
/// ```
#[derive(Debug, Clone)]
pub struct ResourceLimits {
    /// Resource name to semaphore mapping.
    ///
    /// Each semaphore controls the maximum number of concurrent operations
    /// for its associated resource type.
    semaphores: Arc<HashMap<String, Arc<Semaphore>>>,
}

impl ResourceLimits {
    /// Add a resource limit for the specified resource type.
    ///
    /// This creates a semaphore that will limit concurrent access to the
    /// specified resource. Tools with names matching the resource mapping
    /// will be subject to this limit.
    ///
    /// # Parameters
    /// * `resource` - The resource identifier (e.g., "solana_rpc", "evm_rpc")
    /// * `limit` - Maximum number of concurrent operations for this resource
    ///
    /// # Returns
    /// Self, for method chaining
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use riglr_core::ResourceLimits;
    ///
    /// let limits = ResourceLimits::default()
    ///     .with_limit("solana_rpc", 3)     // Limit Solana RPC calls
    ///     .with_limit("database", 10)      // Limit database connections
    ///     .with_limit("external_api", 5);  // Limit external API calls
    /// ```
    pub fn with_limit(mut self, resource: impl Into<String>, limit: usize) -> Self {
        let semaphores = Arc::make_mut(&mut self.semaphores);
        semaphores.insert(resource.into(), Arc::new(Semaphore::new(limit)));
        self
    }

    /// Get the semaphore for a specific resource type.
    ///
    /// This is used internally by the [`ToolWorker`] to acquire permits
    /// before executing tools. Returns `None` if no limit is configured
    /// for the specified resource.
    ///
    /// # Parameters
    /// * `resource` - The resource identifier to look up
    ///
    /// # Returns
    /// * `Some(Arc<Semaphore>)` - If a limit is configured for this resource
    /// * `None` - If no limit is configured (will use default limit)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use riglr_core::ResourceLimits;
    ///
    /// let limits = ResourceLimits::default()
    ///     .with_limit("test_resource", 5);
    ///
    /// assert!(limits.get_semaphore("test_resource").is_some());
    /// assert!(limits.get_semaphore("unknown_resource").is_none());
    /// ```
    pub fn get_semaphore(&self, resource: &str) -> Option<Arc<Semaphore>> {
        self.semaphores.get(resource).cloned()
    }
}

impl Default for ResourceLimits {
    fn default() -> Self {
        let mut semaphores = HashMap::new();
        semaphores.insert("solana_rpc".to_string(), Arc::new(Semaphore::new(5)));
        semaphores.insert("evm_rpc".to_string(), Arc::new(Semaphore::new(10)));
        semaphores.insert("http_api".to_string(), Arc::new(Semaphore::new(20)));
        Self {
            semaphores: Arc::new(semaphores),
        }
    }
}

/// A worker that processes jobs from a queue using registered tools.
///
/// The `ToolWorker` is the core execution engine of the riglr system. It manages
/// registered tools, processes jobs with resilience features, and provides
/// comprehensive monitoring and observability.
///
/// ## Key Features
///
/// - **Resilient execution**: Automatic retries with exponential backoff
/// - **Resource management**: Configurable limits per resource type
/// - **Idempotency support**: Cached results for safe retries
/// - **Comprehensive monitoring**: Built-in metrics and structured logging
/// - **Concurrent processing**: Efficient parallel job execution
///
/// ## Architecture
///
/// The worker operates on a job-based model where:
/// 1. Jobs are dequeued from a [`JobQueue`]
/// 2. Tools are looked up by name and executed
/// 3. Results are processed with retry logic for failures
/// 4. Successful results are optionally cached for idempotency
/// 5. Metrics are updated for monitoring
///
/// ## Examples
///
/// ### Basic Setup
///
/// ```ignore
/// use riglr_core::{
///     ToolWorker, ExecutionConfig, ResourceLimits,
///     idempotency::InMemoryIdempotencyStore
/// };
/// use std::sync::Arc;
///
/// # async fn example() -> anyhow::Result<()> {
/// // Create worker with default configuration
/// let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
///     ExecutionConfig::default()
/// );
///
/// // Add idempotency store for safe retries
/// let store = Arc::new(InMemoryIdempotencyStore::new());
/// let worker = worker.with_idempotency_store(store);
///
/// // Configure resource limits
/// let limits = ResourceLimits::default()
///     .with_limit("solana_rpc", 3)
///     .with_limit("evm_rpc", 5);
/// let worker = worker.with_resource_limits(limits);
/// # Ok(())
/// # }
/// ```
///
/// ### Processing Jobs
///
/// ```ignore
/// use riglr_core::{ToolWorker, Job, Tool, JobResult, ExecutionConfig};
/// use riglr_core::idempotency::InMemoryIdempotencyStore;
/// use async_trait::async_trait;
/// use std::sync::Arc;
///
/// # struct ExampleTool;
/// # #[async_trait]
/// # impl Tool for ExampleTool {
/// #     async fn execute(&self, _: serde_json::Value, _: &crate::provider::ApplicationContext) -> Result<JobResult, ToolError> {
/// #         Ok(JobResult::success(&"example result")?)
/// #     }
/// #     fn name(&self) -> &str { "example" }
/// # }
/// # async fn example() -> anyhow::Result<()> {
/// let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
///     ExecutionConfig::default()
/// );
///
/// // Register tools
/// worker.register_tool(Arc::new(ExampleTool)).await;
///
/// // Process a job
/// let job = Job::new("example", &serde_json::json!({}), 3)?;
/// let result = worker.process_job(job).await.unwrap();
///
/// println!("Job result: {:?}", result);
///
/// // Check metrics
/// let metrics = worker.metrics();
/// println!("Jobs processed: {}",
///     metrics.jobs_processed.load(std::sync::atomic::Ordering::Relaxed));
/// # Ok(())
/// # }
/// ```
pub struct ToolWorker<I: IdempotencyStore + 'static> {
    /// Registered tools, indexed by name for fast lookup
    tools: Arc<DashMap<String, Arc<dyn Tool>>>,

    /// Default semaphore for general concurrency control
    default_semaphore: Arc<Semaphore>,

    /// Resource-specific limits for fine-grained control
    resource_limits: ResourceLimits,

    /// Configuration for retry behavior, timeouts, etc.
    config: ExecutionConfig,

    /// Optional idempotency store for caching results
    idempotency_store: Option<Arc<I>>,

    /// Performance and operational metrics
    metrics: Arc<WorkerMetrics>,

    /// Application context providing access to RPC providers and shared resources
    app_context: crate::provider::ApplicationContext,
}

/// Performance and operational metrics for monitoring worker health.
///
/// These metrics provide insight into worker performance and can be used
/// for monitoring, alerting, and performance optimization.
///
/// All metrics use atomic integers for thread-safe updates and reads.
///
/// ## Metrics Tracked
///
/// - **jobs_processed**: Total number of jobs dequeued and processed
/// - **jobs_succeeded**: Number of jobs that completed successfully
/// - **jobs_failed**: Number of jobs that failed permanently (after all retries)
/// - **jobs_retried**: Total number of retry attempts across all jobs
///
/// ## Examples
///
/// ```ignore
/// use riglr_core::{ToolWorker, ExecutionConfig, idempotency::InMemoryIdempotencyStore};
/// use std::sync::atomic::Ordering;
///
/// # async fn example() {
/// let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
///     ExecutionConfig::default()
/// );
///
/// let metrics = worker.metrics();
///
/// // Read current metrics
/// let processed = metrics.jobs_processed.load(Ordering::Relaxed);
/// let succeeded = metrics.jobs_succeeded.load(Ordering::Relaxed);
/// let failed = metrics.jobs_failed.load(Ordering::Relaxed);
/// let retried = metrics.jobs_retried.load(Ordering::Relaxed);
///
/// println!("Worker Stats:");
/// println!("  Processed: {}", processed);
/// println!("  Succeeded: {}", succeeded);
/// println!("  Failed: {}", failed);
/// println!("  Retried: {}", retried);
/// println!("  Success Rate: {:.2}%",
///     if processed > 0 { (succeeded as f64 / processed as f64) * 100.0 } else { 0.0 });
/// # }
/// ```
#[derive(Debug, Default)]
pub struct WorkerMetrics {
    /// Total number of jobs processed (dequeued and executed)
    pub jobs_processed: std::sync::atomic::AtomicU64,

    /// Number of jobs that completed successfully
    pub jobs_succeeded: std::sync::atomic::AtomicU64,

    /// Number of jobs that failed permanently (after all retries)
    pub jobs_failed: std::sync::atomic::AtomicU64,

    /// Total number of retry attempts across all jobs
    pub jobs_retried: std::sync::atomic::AtomicU64,
}

impl<I: IdempotencyStore + 'static> std::fmt::Debug for ToolWorker<I> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ToolWorker")
            .field("tools_count", &self.tools.len())
            .field("config", &self.config)
            .finish_non_exhaustive()
    }
}

impl<I: IdempotencyStore + 'static> ToolWorker<I> {
    /// Create a new tool worker with the given configuration and application context.
    ///
    /// This creates a worker ready to process jobs, but no tools are registered yet.
    /// Use [`register_tool()`](Self::register_tool) to add tools before processing jobs.
    ///
    /// # Parameters
    /// * `config` - Execution configuration controlling retry behavior, timeouts, etc.
    /// * `app_context` - Application context providing access to RPC providers and shared resources
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use riglr_core::{ToolWorker, ExecutionConfig, idempotency::InMemoryIdempotencyStore, provider::ApplicationContext};
    /// use std::time::Duration;
    /// use riglr_config::Config;
    ///
    /// let exec_config = ExecutionConfig {
    ///     max_concurrency: 20,
    ///     default_timeout: Duration::from_secs(60),
    ///     max_retries: 5,
    ///     ..Default::default()
    /// };
    /// let config = Config::from_env();
    /// let app_context = ApplicationContext::from_config(&config);
    ///
    /// let worker = ToolWorker::<InMemoryIdempotencyStore>::new(exec_config, app_context);
    /// ```
    pub fn new(config: ExecutionConfig, app_context: crate::provider::ApplicationContext) -> Self {
        Self {
            tools: Arc::new(DashMap::new()),
            default_semaphore: Arc::new(Semaphore::new(config.max_concurrency)),
            resource_limits: ResourceLimits::default(),
            config,
            idempotency_store: None,
            metrics: Arc::new(WorkerMetrics::default()),
            app_context,
        }
    }

    /// Configure an idempotency store for result caching.
    ///
    /// When an idempotency store is configured, jobs with idempotency keys
    /// will have their results cached. Subsequent executions with the same
    /// idempotency key will return the cached result instead of re-executing.
    ///
    /// # Parameters
    /// * `store` - The idempotency store implementation to use
    ///
    /// # Returns
    /// Self, for method chaining
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use riglr_core::{ToolWorker, ExecutionConfig, idempotency::InMemoryIdempotencyStore};
    /// use std::sync::Arc;
    ///
    /// let store = Arc::new(InMemoryIdempotencyStore::new());
    /// let worker = ToolWorker::new(ExecutionConfig::default())
    ///     .with_idempotency_store(store);
    /// ```
    pub fn with_idempotency_store(mut self, store: Arc<I>) -> Self {
        self.idempotency_store = Some(store);
        self
    }

    /// Configure custom resource limits.
    ///
    /// Resource limits control how many concurrent operations can run
    /// for each resource type. This prevents overwhelming external
    /// services and provides fine-grained control over resource usage.
    ///
    /// # Parameters
    /// * `limits` - The resource limits configuration to use
    ///
    /// # Returns
    /// Self, for method chaining
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use riglr_core::{ToolWorker, ExecutionConfig, ResourceLimits, idempotency::InMemoryIdempotencyStore};
    ///
    /// let limits = ResourceLimits::default()
    ///     .with_limit("solana_rpc", 3)
    ///     .with_limit("evm_rpc", 8)
    ///     .with_limit("http_api", 15);
    ///
    /// let worker = ToolWorker::<InMemoryIdempotencyStore>::new(ExecutionConfig::default())
    ///     .with_resource_limits(limits);
    /// ```
    pub fn with_resource_limits(mut self, limits: ResourceLimits) -> Self {
        self.resource_limits = limits;
        self
    }

    /// Register a tool with this worker.
    ///
    /// Tools must be registered before they can be executed by jobs.
    /// Each tool is indexed by its name, so tool names must be unique
    /// within a single worker.
    ///
    /// # Parameters
    /// * `tool` - The tool implementation to register
    ///
    /// # Panics
    /// This method does not panic, but if a tool with the same name
    /// is already registered, it will be replaced.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use riglr_core::{ToolWorker, ExecutionConfig, Tool, JobResult, idempotency::InMemoryIdempotencyStore};
    /// use async_trait::async_trait;
    /// use std::sync::Arc;
    ///
    /// struct CalculatorTool;
    ///
    /// #[async_trait]
    /// impl Tool for CalculatorTool {
    ///     async fn execute(&self, params: serde_json::Value, _context: &ApplicationContext) -> Result<JobResult, ToolError> {
    ///         let a = params["a"].as_f64().unwrap_or(0.0);
    ///         let b = params["b"].as_f64().unwrap_or(0.0);
    ///         Ok(JobResult::success(&(a + b))?)
    ///     }
    ///
    ///     fn name(&self) -> &str {
    ///         "calculator"
    ///     }
    /// }
    ///
    /// # async fn example() {
    /// let worker = ToolWorker::<InMemoryIdempotencyStore>::new(ExecutionConfig::default());
    /// worker.register_tool(Arc::new(CalculatorTool)).await;
    /// # }
    /// ```
    pub async fn register_tool(&self, tool: Arc<dyn Tool>) {
        self.tools.insert(tool.name().to_string(), tool);
    }

    /// Get access to worker metrics.
    ///
    /// The returned metrics can be used for monitoring worker performance
    /// and health. All metrics are thread-safe and can be read at any time.
    ///
    /// # Returns
    /// A reference to the worker's metrics
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use riglr_core::{ToolWorker, ExecutionConfig, idempotency::InMemoryIdempotencyStore};
    /// use std::sync::atomic::Ordering;
    ///
    /// let worker = ToolWorker::<InMemoryIdempotencyStore>::new(ExecutionConfig::default());
    /// let metrics = worker.metrics();
    ///
    /// println!("Jobs processed: {}",
    ///     metrics.jobs_processed.load(Ordering::Relaxed));
    /// println!("Success rate: {:.2}%", {
    ///     let processed = metrics.jobs_processed.load(Ordering::Relaxed);
    ///     let succeeded = metrics.jobs_succeeded.load(Ordering::Relaxed);
    ///     if processed > 0 { (succeeded as f64 / processed as f64) * 100.0 } else { 0.0 }
    /// });
    /// ```
    pub fn metrics(&self) -> &WorkerMetrics {
        &self.metrics
    }

    /// Process a single job with all resilience features.
    ///
    /// Returns:
    /// - `Ok(JobResult)` - The job was processed (successfully or with business logic failure)
    /// - `Err(WorkerError)` - System-level worker failure (tool not found, semaphore issues, etc.)
    pub async fn process_job(&self, mut job: Job) -> Result<JobResult, WorkerError> {
        // Check idempotency cache first
        if let Some(cached_result) = self.check_idempotency_cache(&job).await? {
            return Ok(Arc::try_unwrap(cached_result).unwrap_or_else(|arc| (*arc).clone()));
        }

        // Apply rate limiting for operations within a SignerContext that has a user_id
        if let Ok(signer) = SignerContext::current().await {
            if let Some(user_id) = signer.user_id() {
                if let Err(rate_limit_error) =
                    self.app_context.rate_limiter.check_rate_limit(&user_id)
                {
                    // Convert rate limit error to a JobResult::Failure
                    return Ok(JobResult::Failure {
                        error: rate_limit_error,
                    });
                }
            }
        }

        // Acquire appropriate semaphore
        let _permit = self.acquire_semaphore(&job.tool_name).await.map_err(|e| {
            WorkerError::SemaphoreAcquisition {
                tool_name: job.tool_name.clone(),
                source_message: e.to_string(),
            }
        })?;

        // Get the tool for this job
        let tool = self.get_tool(&job.tool_name).await?;

        // Execute with retries
        let result = self.execute_with_retries(tool, &mut job).await;

        // Cache successful results
        if let Ok(ref job_result) = result {
            self.cache_result(&job, job_result).await;
        }

        result
    }

    /// Check if there's a cached result for this job
    async fn check_idempotency_cache(
        &self,
        job: &Job,
    ) -> Result<Option<Arc<JobResult>>, WorkerError> {
        if let Some(ref idempotency_key) = job.idempotency_key {
            if self.config.enable_idempotency {
                if let Some(ref store) = self.idempotency_store {
                    match store.get(idempotency_key).await {
                        Ok(Some(cached_result)) => {
                            info!(
                                "Returning cached result for idempotency key: {}",
                                idempotency_key
                            );
                            return Ok(Some(cached_result));
                        }
                        Ok(None) => {} // No cached result
                        Err(e) => {
                            return Err(WorkerError::IdempotencyStore {
                                source_message: e.to_string(),
                            });
                        }
                    }
                }
            }
        }
        Ok(None)
    }

    /// Get a tool from the registry
    async fn get_tool(&self, tool_name: &str) -> Result<Arc<dyn Tool>, WorkerError> {
        self.tools
            .get(tool_name)
            .ok_or_else(|| WorkerError::ToolNotFound {
                tool_name: tool_name.to_string(),
            })
            .map(|entry| (*entry).clone())
    }

    /// Execute a tool with retry logic using unified retry helper
    async fn execute_with_retries(
        &self,
        tool: Arc<dyn Tool>,
        job: &mut Job,
    ) -> Result<JobResult, WorkerError> {
        use crate::retry::{retry_async, ErrorClass, RetryConfig};

        // Create retry config from worker config
        let retry_config = RetryConfig {
            max_retries: job.max_retries,
            base_delay_ms: self.config.initial_retry_delay.as_millis() as u64,
            max_delay_ms: self.config.max_retry_delay.as_millis() as u64,
            backoff_multiplier: 2.0,
            use_jitter: true,
        };

        // Use unified retry helper
        let result = retry_async(
            || async { self.execute_single_attempt(&tool, &job.params).await },
            |error| {
                // Classify error based on ToolError's is_retriable
                if error.is_retriable() {
                    ErrorClass::Retryable
                } else {
                    ErrorClass::Permanent
                }
            },
            &retry_config,
            &format!("job_{}", job.job_id),
        )
        .await;

        // Update metrics based on result
        match result {
            Ok(job_result) => {
                self.metrics
                    .jobs_succeeded
                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                Ok(job_result)
            }
            Err(tool_error) => {
                self.metrics
                    .jobs_failed
                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                // Track retries that occurred - the retry helper manages the actual retries
                if retry_config.max_retries > 0 {
                    self.metrics
                        .jobs_retried
                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                }
                Ok(JobResult::Failure { error: tool_error })
            }
        }
    }

    /// Execute a single attempt of a tool
    async fn execute_single_attempt(
        &self,
        tool: &Arc<dyn Tool>,
        params: &serde_json::Value,
    ) -> Result<JobResult, ToolError> {
        // Execute with timeout
        let result = tokio::time::timeout(
            self.config.default_timeout,
            tool.execute(params.clone(), &self.app_context),
        )
        .await;

        match result {
            Ok(Ok(job_result)) => Ok(job_result),
            Ok(Err(e)) => {
                // Propagate the ToolError directly to preserve its structure
                warn!("Tool execution failed: {}", e);
                Err(e)
            }
            Err(_) => {
                let error_msg = format!(
                    "Tool execution timed out after {:?}",
                    self.config.default_timeout
                );
                warn!("{}", error_msg);
                // Timeout errors are retriable
                Err(ToolError::retriable_string(error_msg))
            }
        }
    }

    // Note: create_backoff_strategy and wait_with_backoff methods removed
    // as they are now handled by the unified retry helper in retry.rs

    /// Cache a successful result
    async fn cache_result(&self, job: &Job, job_result: &JobResult) {
        if let Some(ref idempotency_key) = job.idempotency_key {
            if self.config.enable_idempotency {
                if let Some(ref store) = self.idempotency_store {
                    let _ = store
                        .set(
                            idempotency_key,
                            Arc::new(job_result.clone()),
                            self.config.idempotency_ttl,
                        )
                        .await;
                }
            }
        }
    }

    /// Acquire the appropriate semaphore for a tool
    async fn acquire_semaphore(
        &self,
        tool_name: &str,
    ) -> Result<OwnedSemaphorePermit, Box<dyn std::error::Error + Send + Sync>> {
        // Check if there's a specific resource limit for this tool
        let resource_name = match tool_name {
            name if name.starts_with("solana_") => "solana_rpc",
            name if name.starts_with("evm_") => "evm_rpc",
            name if name.starts_with("web_") => "http_api",
            _ => "",
        };

        if !resource_name.is_empty() {
            if let Some(semaphore) = self.resource_limits.get_semaphore(resource_name) {
                return Ok(semaphore.acquire_owned().await?);
            }
        }

        // Fall back to default semaphore
        Ok(self.default_semaphore.clone().acquire_owned().await?)
    }

    /// Start the worker loop, processing jobs from the given queue.
    ///
    /// The worker will continue processing jobs until the provided cancellation token
    /// is cancelled. This allows for graceful shutdown where in-flight jobs can complete
    /// before the worker stops.
    ///
    /// # Parameters
    /// * `queue` - The job queue to process jobs from
    /// * `cancellation_token` - Token to signal when the worker should stop
    ///
    /// # Examples
    ///
    /// ```rust
    /// use riglr_core::{ToolWorker, ExecutionConfig, idempotency::InMemoryIdempotencyStore};
    /// use riglr_core::provider::ApplicationContext;
    /// use riglr_core::queue::InMemoryJobQueue;
    /// use riglr_config::ConfigBuilder;
    /// use tokio_util::sync::CancellationToken;
    /// use std::sync::Arc;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let config = ConfigBuilder::default().build().unwrap();
    /// let app_context = ApplicationContext::from_config(&config);
    /// let worker = ToolWorker::<InMemoryIdempotencyStore>::new(ExecutionConfig::default(), app_context);
    /// let queue = Arc::new(InMemoryJobQueue::new());
    /// let cancellation_token = CancellationToken::new();
    ///
    /// // Start worker in background
    /// let token_clone = cancellation_token.clone();
    /// let worker_handle = tokio::spawn(async move {
    ///     worker.run(queue, token_clone).await
    /// });
    ///
    /// // Later, signal shutdown
    /// cancellation_token.cancel();
    /// // Await the task and ignore the inner result for simplicity in docs
    /// let _ = worker_handle.await;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn run<Q: JobQueue>(
        &self,
        queue: Arc<Q>,
        cancellation_token: tokio_util::sync::CancellationToken,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        info!(
            "Starting ToolWorker with {} tools registered",
            self.tools.len()
        );

        while !cancellation_token.is_cancelled() {
            tokio::select! {
                // Check for cancellation
                _ = cancellation_token.cancelled() => {
                    info!("Worker shutdown requested, stopping job processing");
                    break;
                }

                // Try to dequeue and process jobs
                result = queue.dequeue_with_timeout(Duration::from_secs(5)) => {
                    match result {
                        Ok(Some(job)) => {
                            let job_id = job.job_id;
                            let tool_name = job.tool_name.clone();

                            self.metrics
                                .jobs_processed
                                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);

                            // Spawn task to process job asynchronously
                            let worker = self.clone();
                            tokio::spawn(async move {
                                match worker.process_job(job).await {
                                    Ok(job_result) => {
                                        if job_result.is_success() {
                                            info!("Job {} ({}) completed successfully", job_id, tool_name);
                                        } else {
                                            warn!(
                                                "Job {} ({}) failed: {:?}",
                                                job_id, tool_name, job_result
                                            );
                                        }
                                    }
                                    Err(e) => {
                                        error!("Job {} ({}) processing error: {}", job_id, tool_name, e);
                                    }
                                }
                            });
                        }
                        Ok(None) => {
                            // No jobs available, continue
                            debug!("No jobs available in queue");
                        }
                        Err(e) => {
                            error!("Failed to dequeue job: {}", e);
                            tokio::time::sleep(Duration::from_secs(1)).await;
                        }
                    }
                }
            }
        }

        info!("ToolWorker shutdown completed");
        Ok(())
    }
}

// Implement Clone for ToolWorker to enable spawning tasks
impl<I: IdempotencyStore + 'static> Clone for ToolWorker<I> {
    fn clone(&self) -> Self {
        Self {
            tools: self.tools.clone(),
            default_semaphore: self.default_semaphore.clone(),
            resource_limits: self.resource_limits.clone(),
            config: self.config.clone(),
            idempotency_store: self.idempotency_store.clone(),
            metrics: self.metrics.clone(),
            app_context: self.app_context.clone(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::idempotency::InMemoryIdempotencyStore;
    use crate::jobs::Job;
    use crate::provider::ApplicationContext;
    use uuid::Uuid;

    fn test_app_context() -> ApplicationContext {
        // Use default configuration for tests
        ApplicationContext::default()
    }

    struct MockTool {
        name: String,
        should_fail: bool,
    }

    struct RetriableMockTool {
        name: String,
    }

    #[async_trait]
    impl Tool for MockTool {
        async fn execute(
            &self,
            _params: serde_json::Value,
            _context: &crate::provider::ApplicationContext,
        ) -> Result<JobResult, ToolError> {
            if self.should_fail {
                Err(ToolError::permanent_string("Mock failure"))
            } else {
                Ok(JobResult::Success {
                    value: serde_json::json!({"result": "success"}),
                    tx_hash: None,
                })
            }
        }

        fn name(&self) -> &str {
            &self.name
        }

        fn description(&self) -> &str {
            ""
        }

        fn schema(&self) -> serde_json::Value {
            serde_json::json!({
                "type": "object",
                "additionalProperties": true
            })
        }
    }

    #[async_trait]
    impl Tool for RetriableMockTool {
        async fn execute(
            &self,
            _params: serde_json::Value,
            _context: &crate::provider::ApplicationContext,
        ) -> Result<JobResult, ToolError> {
            Err(ToolError::retriable_string("Mock retriable failure"))
        }

        fn name(&self) -> &str {
            &self.name
        }

        fn description(&self) -> &str {
            ""
        }

        fn schema(&self) -> serde_json::Value {
            serde_json::json!({
                "type": "object",
                "additionalProperties": true
            })
        }
    }

    #[tokio::test]
    async fn test_tool_worker_process_job() {
        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
            ExecutionConfig::default(),
            test_app_context(),
        );
        let tool = Arc::new(MockTool {
            name: "test_tool".to_string(),
            should_fail: false,
        });
        worker.register_tool(tool).await;

        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "test_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None,
            max_retries: 3,
            retry_count: 0,
        };

        let result = worker.process_job(job).await.unwrap();
        match result {
            JobResult::Success { .. } => (),
            _ => panic!("Expected success"),
        }
    }

    #[tokio::test]
    async fn test_tool_worker_with_idempotency() {
        let store = Arc::new(InMemoryIdempotencyStore::new());
        let worker = ToolWorker::new(ExecutionConfig::default(), test_app_context())
            .with_idempotency_store(store.clone());

        let tool = Arc::new(MockTool {
            name: "test_tool".to_string(),
            should_fail: false,
        });
        worker.register_tool(tool).await;

        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "test_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: Some("test_key".to_string()),
            max_retries: 3,
            retry_count: 0,
        };

        // First execution
        let result1 = worker.process_job(job.clone()).await.unwrap();
        assert!(result1.is_success());

        // Second execution should return cached result
        let result2 = worker.process_job(job).await.unwrap();
        assert!(result2.is_success());
    }

    #[tokio::test]
    async fn test_tool_worker_with_retries() {
        let config = ExecutionConfig {
            initial_retry_delay: Duration::from_millis(10),
            ..Default::default()
        };

        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(config, test_app_context());
        let tool = Arc::new(MockTool {
            name: "test_tool".to_string(),
            should_fail: true,
        });
        worker.register_tool(tool).await;

        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "test_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None,
            max_retries: 2,
            retry_count: 0,
        };

        let result = worker.process_job(job).await.unwrap();
        match result {
            JobResult::Failure { .. } => {
                assert!(!result.is_retriable()); // Should not be retriable after exhausting retries
            }
            _ => panic!("Expected failure"),
        }
    }

    #[tokio::test]
    async fn test_tool_worker_tool_not_found() {
        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
            ExecutionConfig::default(),
            test_app_context(),
        );

        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "nonexistent_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None,
            max_retries: 0,
            retry_count: 0,
        };

        let result = worker.process_job(job).await;
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Tool 'nonexistent_tool' not found"));
    }

    #[tokio::test]
    async fn test_tool_worker_timeout() {
        let config = ExecutionConfig {
            default_timeout: Duration::from_millis(10), // Very short timeout
            ..Default::default()
        };

        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(config, test_app_context());
        let tool = Arc::new(SlowMockTool {
            name: "slow_tool".to_string(),
            delay: Duration::from_millis(100),
        });
        worker.register_tool(tool).await;

        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "slow_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None,
            max_retries: 1,
            retry_count: 0,
        };

        let result = worker.process_job(job).await.unwrap();
        match result {
            JobResult::Failure { error, .. } => {
                assert!(error.to_string().to_lowercase().contains("timed out"));
            }
            _ => panic!("Expected timeout failure"),
        }
    }

    #[tokio::test]
    async fn test_tool_worker_with_resource_limits() {
        let config = ExecutionConfig::default();
        let limits = ResourceLimits::default()
            .with_limit("solana_rpc", 2)
            .with_limit("evm_rpc", 3);

        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(config, test_app_context())
            .with_resource_limits(limits);

        // Test semaphore acquisition for different tool types
        let solana_tool = Arc::new(MockTool {
            name: "solana_test".to_string(),
            should_fail: false,
        });
        let evm_tool = Arc::new(MockTool {
            name: "evm_test".to_string(),
            should_fail: false,
        });
        let web_tool = Arc::new(MockTool {
            name: "web_test".to_string(),
            should_fail: false,
        });
        let other_tool = Arc::new(MockTool {
            name: "other_test".to_string(),
            should_fail: false,
        });

        worker.register_tool(solana_tool).await;
        worker.register_tool(evm_tool).await;
        worker.register_tool(web_tool).await;
        worker.register_tool(other_tool).await;

        // Test different tool name patterns
        let jobs = vec![
            Job {
                job_id: Uuid::new_v4(),
                tool_name: "solana_test".to_string(),
                params: serde_json::json!({}),
                idempotency_key: None,
                max_retries: 0,
                retry_count: 0,
            },
            Job {
                job_id: Uuid::new_v4(),
                tool_name: "evm_test".to_string(),
                params: serde_json::json!({}),
                idempotency_key: None,
                max_retries: 0,
                retry_count: 0,
            },
            Job {
                job_id: Uuid::new_v4(),
                tool_name: "web_test".to_string(),
                params: serde_json::json!({}),
                idempotency_key: None,
                max_retries: 0,
                retry_count: 0,
            },
            Job {
                job_id: Uuid::new_v4(),
                tool_name: "other_test".to_string(),
                params: serde_json::json!({}),
                idempotency_key: None,
                max_retries: 0,
                retry_count: 0,
            },
        ];

        // All should succeed
        for job in jobs {
            let result = worker.process_job(job).await.unwrap();
            assert!(result.is_success());
        }
    }

    #[tokio::test]
    async fn test_tool_worker_idempotency_disabled() {
        let config = ExecutionConfig {
            enable_idempotency: false,
            ..Default::default()
        };

        let store = Arc::new(InMemoryIdempotencyStore::new());
        let worker =
            ToolWorker::new(config, test_app_context()).with_idempotency_store(store.clone());

        let tool = Arc::new(MockTool {
            name: "test_tool".to_string(),
            should_fail: false,
        });
        worker.register_tool(tool).await;

        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "test_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: Some("test_key".to_string()),
            max_retries: 0,
            retry_count: 0,
        };

        // First execution
        let result1 = worker.process_job(job.clone()).await.unwrap();
        assert!(result1.is_success());

        // Second execution should NOT use cache due to disabled idempotency
        let result2 = worker.process_job(job).await.unwrap();
        assert!(result2.is_success());

        // Verify the key was never set in the store
        assert!(store.get("test_key").await.unwrap().is_none());
    }

    #[tokio::test]
    async fn test_tool_worker_metrics() {
        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
            ExecutionConfig::default(),
            test_app_context(),
        );
        let success_tool = Arc::new(MockTool {
            name: "success_tool".to_string(),
            should_fail: false,
        });
        let fail_tool = Arc::new(RetriableMockTool {
            name: "fail_tool".to_string(),
        });

        worker.register_tool(success_tool).await;
        worker.register_tool(fail_tool).await;

        let metrics = worker.metrics();

        // Initial state
        assert_eq!(
            metrics
                .jobs_processed
                .load(std::sync::atomic::Ordering::Relaxed),
            0
        );
        assert_eq!(
            metrics
                .jobs_succeeded
                .load(std::sync::atomic::Ordering::Relaxed),
            0
        );
        assert_eq!(
            metrics
                .jobs_failed
                .load(std::sync::atomic::Ordering::Relaxed),
            0
        );
        assert_eq!(
            metrics
                .jobs_retried
                .load(std::sync::atomic::Ordering::Relaxed),
            0
        );

        // Process successful job
        let success_job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "success_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None,
            max_retries: 0,
            retry_count: 0,
        };
        worker.process_job(success_job).await.unwrap();
        assert_eq!(
            metrics
                .jobs_succeeded
                .load(std::sync::atomic::Ordering::Relaxed),
            1
        );

        // Process failing job with retries
        let fail_job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "fail_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None,
            max_retries: 2,
            retry_count: 0,
        };
        worker.process_job(fail_job).await.unwrap();
        assert_eq!(
            metrics
                .jobs_failed
                .load(std::sync::atomic::Ordering::Relaxed),
            1
        );
        assert_eq!(
            metrics
                .jobs_retried
                .load(std::sync::atomic::Ordering::Relaxed),
            1
        );
    }

    #[tokio::test]
    async fn test_execution_config_default() {
        let config = ExecutionConfig::default();
        assert_eq!(config.max_concurrency, 10);
        assert_eq!(config.default_timeout, Duration::from_secs(30));
        assert_eq!(config.max_retries, 3);
        assert_eq!(config.initial_retry_delay, Duration::from_millis(100));
        assert_eq!(config.max_retry_delay, Duration::from_secs(10));
        assert_eq!(config.idempotency_ttl, Duration::from_secs(3600));
        assert!(config.enable_idempotency);
    }

    #[tokio::test]
    async fn test_resource_limits() {
        let limits = ResourceLimits::default()
            .with_limit("test_resource", 5)
            .with_limit("another_resource", 10);

        assert!(limits.get_semaphore("test_resource").is_some());
        assert!(limits.get_semaphore("another_resource").is_some());
        assert!(limits.get_semaphore("nonexistent").is_none());

        let default_limits = ResourceLimits::default();
        assert!(default_limits.get_semaphore("solana_rpc").is_some());
        assert!(default_limits.get_semaphore("evm_rpc").is_some());
        assert!(default_limits.get_semaphore("http_api").is_some());
    }

    #[tokio::test]
    async fn test_worker_metrics_default() {
        let metrics = WorkerMetrics::default();
        assert_eq!(
            metrics
                .jobs_processed
                .load(std::sync::atomic::Ordering::Relaxed),
            0
        );
        assert_eq!(
            metrics
                .jobs_succeeded
                .load(std::sync::atomic::Ordering::Relaxed),
            0
        );
        assert_eq!(
            metrics
                .jobs_failed
                .load(std::sync::atomic::Ordering::Relaxed),
            0
        );
        assert_eq!(
            metrics
                .jobs_retried
                .load(std::sync::atomic::Ordering::Relaxed),
            0
        );
    }

    #[tokio::test]
    async fn test_tool_worker_clone() {
        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
            ExecutionConfig::default(),
            test_app_context(),
        );
        let tool = Arc::new(MockTool {
            name: "test_tool".to_string(),
            should_fail: false,
        });
        worker.register_tool(tool).await;

        let cloned_worker = worker.clone();

        // Both workers should have access to the same tools
        assert_eq!(worker.tools.len(), 1);
        assert_eq!(cloned_worker.tools.len(), 1);

        // Test processing with cloned worker
        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "test_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None,
            max_retries: 0,
            retry_count: 0,
        };

        let result = cloned_worker.process_job(job).await.unwrap();
        assert!(result.is_success());
    }

    #[tokio::test]
    async fn test_tool_worker_run_loop() {
        use crate::queue::InMemoryJobQueue;

        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
            ExecutionConfig::default(),
            test_app_context(),
        );
        let tool = Arc::new(MockTool {
            name: "test_tool".to_string(),
            should_fail: false,
        });
        worker.register_tool(tool).await;

        let queue = Arc::new(InMemoryJobQueue::new());

        // Enqueue a job
        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "test_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None,
            max_retries: 0,
            retry_count: 0,
        };
        queue.enqueue(job).await.unwrap();

        // Start the worker run loop with cancellation token
        let worker_clone = worker.clone();
        let queue_clone = queue.clone();
        let cancellation_token = tokio_util::sync::CancellationToken::new();
        let token_clone = cancellation_token.clone();

        let handle = tokio::spawn(async move { worker_clone.run(queue_clone, token_clone).await });

        // Give it time to process the job
        tokio::time::sleep(Duration::from_millis(50)).await;

        // Signal shutdown
        cancellation_token.cancel();

        // Check that metrics were updated
        let metrics = worker.metrics();
        assert!(
            metrics
                .jobs_processed
                .load(std::sync::atomic::Ordering::Relaxed)
                > 0
        );

        handle.await.unwrap().unwrap();
    }

    #[tokio::test]
    async fn test_idempotency_cache_hit() {
        let store = Arc::new(InMemoryIdempotencyStore::new());
        let worker = ToolWorker::new(ExecutionConfig::default(), test_app_context())
            .with_idempotency_store(store.clone());

        let tool = Arc::new(MockTool {
            name: "test_tool".to_string(),
            should_fail: false,
        });
        worker.register_tool(tool).await;

        // Pre-populate the cache
        let cached_result = JobResult::Success {
            value: serde_json::json!({"cached": true}),
            tx_hash: Some("cached_tx_hash".to_string()),
        };
        store
            .set(
                "cache_key",
                Arc::new(cached_result),
                Duration::from_secs(60),
            )
            .await
            .unwrap();

        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "test_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: Some("cache_key".to_string()),
            max_retries: 0,
            retry_count: 0,
        };

        // Should return cached result without executing the tool
        let result = worker.process_job(job).await.unwrap();
        match result {
            JobResult::Success { value, tx_hash } => {
                assert_eq!(value, serde_json::json!({"cached": true}));
                assert_eq!(tx_hash, Some("cached_tx_hash".to_string()));
            }
            _ => panic!("Expected cached success result"),
        }
    }

    #[tokio::test]
    async fn test_tool_worker_unknown_error_fallback() {
        // Create a worker with a job that will fail with max retries
        // but have no last_error set to trigger the "Unknown error" fallback
        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
            ExecutionConfig::default(),
            test_app_context(),
        );

        // Don't register any tool - this will cause tool not found error
        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "nonexistent_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None,
            max_retries: 0,
            retry_count: 0,
        };

        // This should fail with tool not found, not unknown error
        let result = worker.process_job(job).await;
        assert!(result.is_err());

        // The unknown error fallback is actually hard to trigger in normal flow
        // It would only happen if there's a bug in the retry logic where
        // attempts > max_retries but last_error is None
    }

    #[tokio::test]
    async fn test_run_loop_error_handling() {
        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
            ExecutionConfig::default(),
            test_app_context(),
        );
        let error_queue = Arc::new(ErrorQueue::default());

        // Start run loop with cancellation token
        let worker_clone = worker.clone();
        let queue_clone = error_queue.clone();
        let cancellation_token = tokio_util::sync::CancellationToken::new();
        let token_clone = cancellation_token.clone();

        let handle = tokio::spawn(async move { worker_clone.run(queue_clone, token_clone).await });

        // Give it time to encounter the error
        tokio::time::sleep(Duration::from_millis(50)).await;

        // Signal shutdown
        cancellation_token.cancel();
        handle.await.unwrap().unwrap();
    }

    #[tokio::test]
    async fn test_run_loop_empty_queue() {
        use crate::queue::InMemoryJobQueue;

        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
            ExecutionConfig::default(),
            test_app_context(),
        );
        let queue = Arc::new(InMemoryJobQueue::new());

        // Start run loop with cancellation token - should encounter Ok(None) from empty queue
        let worker_clone = worker.clone();
        let queue_clone = queue.clone();
        let cancellation_token = tokio_util::sync::CancellationToken::new();
        let token_clone = cancellation_token.clone();

        let handle = tokio::spawn(async move { worker_clone.run(queue_clone, token_clone).await });

        // Give it time to process
        tokio::time::sleep(Duration::from_millis(50)).await;

        // Signal shutdown
        cancellation_token.cancel();
        handle.await.unwrap().unwrap();
    }

    #[tokio::test]
    async fn test_run_loop_with_failing_jobs() {
        use crate::queue::InMemoryJobQueue;

        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
            ExecutionConfig::default(),
            test_app_context(),
        );
        let fail_tool = Arc::new(MockTool {
            name: "fail_tool".to_string(),
            should_fail: true,
        });
        worker.register_tool(fail_tool).await;

        let queue = Arc::new(InMemoryJobQueue::new());

        // Enqueue a failing job
        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "fail_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None,
            max_retries: 0,
            retry_count: 0,
        };
        queue.enqueue(job).await.unwrap();

        // Start run loop with cancellation token
        let worker_clone = worker.clone();
        let queue_clone = queue.clone();
        let cancellation_token = tokio_util::sync::CancellationToken::new();
        let token_clone = cancellation_token.clone();

        let handle = tokio::spawn(async move { worker_clone.run(queue_clone, token_clone).await });

        // Give it time to process the failing job
        tokio::time::sleep(Duration::from_millis(50)).await;

        // Signal shutdown
        cancellation_token.cancel();
        handle.await.unwrap().unwrap();

        // Verify metrics were updated
        let metrics = worker.metrics();
        assert!(
            metrics
                .jobs_processed
                .load(std::sync::atomic::Ordering::Relaxed)
                > 0
        );
    }

    #[tokio::test]
    async fn test_comprehensive_metrics_tracking() {
        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
            ExecutionConfig::default(),
            test_app_context(),
        );
        let success_tool = Arc::new(MockTool {
            name: "success_tool".to_string(),
            should_fail: false,
        });
        let fail_tool = Arc::new(RetriableMockTool {
            name: "fail_tool".to_string(),
        });
        worker.register_tool(success_tool).await;
        worker.register_tool(fail_tool).await;

        let metrics = worker.metrics();

        // Process a successful job
        let success_job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "success_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None,
            max_retries: 0,
            retry_count: 0,
        };
        let result = worker.process_job(success_job).await.unwrap();
        assert!(result.is_success());

        // Verify jobs_succeeded was incremented (line 232)
        assert_eq!(
            metrics
                .jobs_succeeded
                .load(std::sync::atomic::Ordering::Relaxed),
            1
        );

        // Process a failing job with retries
        let fail_job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "fail_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None,
            max_retries: 2,
            retry_count: 0,
        };
        let result = worker.process_job(fail_job).await.unwrap();
        assert!(!result.is_success());

        // Verify jobs_retried was incremented (line 250)
        assert_eq!(
            metrics
                .jobs_retried
                .load(std::sync::atomic::Ordering::Relaxed),
            1
        );

        // Verify jobs_failed was incremented (line 264)
        assert_eq!(
            metrics
                .jobs_failed
                .load(std::sync::atomic::Ordering::Relaxed),
            1
        );
    }

    #[tokio::test]
    async fn test_debug_logging_in_retries() {
        let config = ExecutionConfig {
            initial_retry_delay: Duration::from_millis(1),
            ..Default::default()
        };

        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(config, test_app_context());
        let tool = Arc::new(MockTool {
            name: "retry_tool".to_string(),
            should_fail: true,
        });
        worker.register_tool(tool).await;

        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "retry_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None,
            max_retries: 1,
            retry_count: 0,
        };

        // This should trigger debug logging in the retry loop (lines 205-208)
        let _result = worker.process_job(job).await.unwrap();
    }

    #[tokio::test]
    async fn test_worker_startup_logging() {
        use crate::queue::InMemoryJobQueue;

        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
            ExecutionConfig::default(),
            test_app_context(),
        );
        let tool = Arc::new(MockTool {
            name: "startup_tool".to_string(),
            should_fail: false,
        });
        worker.register_tool(tool).await;

        let queue = Arc::new(InMemoryJobQueue::new());

        // This should trigger the startup info log
        let worker_clone = worker.clone();
        let queue_clone = queue.clone();
        let cancellation_token = tokio_util::sync::CancellationToken::new();
        let token_clone = cancellation_token.clone();

        let handle = tokio::spawn(async move { worker_clone.run(queue_clone, token_clone).await });

        // Give it time to start up
        tokio::time::sleep(Duration::from_millis(10)).await;

        // Signal shutdown
        cancellation_token.cancel();
        handle.await.unwrap().unwrap();
    }

    #[tokio::test]
    async fn test_timeout_specific_error() {
        let config = ExecutionConfig {
            default_timeout: Duration::from_millis(1), // Very short timeout
            ..Default::default()
        };

        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(config, test_app_context());
        let tool = Arc::new(SlowMockTool {
            name: "timeout_tool".to_string(),
            delay: Duration::from_millis(50),
        });
        worker.register_tool(tool).await;

        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "timeout_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None,
            max_retries: 0,
            retry_count: 0,
        };

        // This should specifically hit the timeout error assignment (line 240)
        let result = worker.process_job(job).await.unwrap();
        match result {
            JobResult::Failure { error, .. } => {
                assert!(error.to_string().to_lowercase().contains("timed out"));
            }
            _ => panic!("Expected timeout failure"),
        }
    }

    #[tokio::test]
    async fn test_resource_matching_edge_cases() {
        let limits = ResourceLimits::default()
            .with_limit("solana_rpc", 1)
            .with_limit("evm_rpc", 1);

        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
            ExecutionConfig::default(),
            test_app_context(),
        )
        .with_resource_limits(limits);

        // Register tools with different name patterns to exercise line 278
        let solana_tool = Arc::new(MockTool {
            name: "solana_balance".to_string(), // Should match solana_ pattern
            should_fail: false,
        });
        let evm_tool = Arc::new(MockTool {
            name: "evm_call".to_string(), // Should match evm_ pattern
            should_fail: false,
        });
        let web_tool = Arc::new(MockTool {
            name: "web_fetch".to_string(), // Should match web_ pattern
            should_fail: false,
        });
        let other_tool = Arc::new(MockTool {
            name: "other_operation".to_string(), // Should use default semaphore
            should_fail: false,
        });

        worker.register_tool(solana_tool).await;
        worker.register_tool(evm_tool).await;
        worker.register_tool(web_tool).await;
        worker.register_tool(other_tool).await;

        // Process jobs to exercise the acquire_semaphore method
        let job1 = Job {
            job_id: Uuid::new_v4(),
            tool_name: "solana_balance".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None,
            max_retries: 0,
            retry_count: 0,
        };

        let _result = worker.process_job(job1).await.unwrap();

        let job2 = Job {
            job_id: Uuid::new_v4(),
            tool_name: "other_operation".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None,
            max_retries: 0,
            retry_count: 0,
        };

        let _result = worker.process_job(job2).await.unwrap();
    }

    #[tokio::test]
    async fn test_execution_config_custom_values() {
        let config = ExecutionConfig {
            max_concurrency: 25,
            default_timeout: Duration::from_secs(60),
            max_retries: 5,
            initial_retry_delay: Duration::from_millis(200),
            max_retry_delay: Duration::from_secs(20),
            idempotency_ttl: Duration::from_secs(7200),
            enable_idempotency: false,
        };

        assert_eq!(config.max_concurrency, 25);
        assert_eq!(config.default_timeout, Duration::from_secs(60));
        assert_eq!(config.max_retries, 5);
        assert_eq!(config.initial_retry_delay, Duration::from_millis(200));
        assert_eq!(config.max_retry_delay, Duration::from_secs(20));
        assert_eq!(config.idempotency_ttl, Duration::from_secs(7200));
        assert!(!config.enable_idempotency);
    }

    #[tokio::test]
    async fn test_resource_limits_new() {
        let limits = ResourceLimits::default();
        assert!(limits.get_semaphore("any_resource").is_none());
    }

    #[tokio::test]
    async fn test_resource_limits_with_limit_chaining() {
        let limits = ResourceLimits::default()
            .with_limit("first", 1)
            .with_limit("second", 2)
            .with_limit("third", 3);

        assert!(limits.get_semaphore("first").is_some());
        assert!(limits.get_semaphore("second").is_some());
        assert!(limits.get_semaphore("third").is_some());
        assert!(limits.get_semaphore("fourth").is_none());
    }

    #[tokio::test]
    async fn test_tool_worker_new_custom_config() {
        let config = ExecutionConfig {
            max_concurrency: 5,
            ..Default::default()
        };
        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(config, test_app_context());

        // Verify worker was created with custom concurrency
        // We can't directly access default_semaphore, but we can verify through the config
        assert_eq!(worker.config.max_concurrency, 5);
    }

    #[tokio::test]
    async fn test_tool_worker_register_tool_replacement() {
        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
            ExecutionConfig::default(),
            test_app_context(),
        );

        // Register initial tool
        let tool1 = Arc::new(MockTool {
            name: "test_tool".to_string(),
            should_fail: false,
        });
        worker.register_tool(tool1).await;
        assert_eq!(worker.tools.len(), 1);

        // Register tool with same name - should replace
        let tool2 = Arc::new(MockTool {
            name: "test_tool".to_string(),
            should_fail: true,
        });
        worker.register_tool(tool2).await;
        assert_eq!(worker.tools.len(), 1);

        // Verify the new tool was used (it should fail)
        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "test_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None,
            max_retries: 0,
            retry_count: 0,
        };

        let result = worker.process_job(job).await.unwrap();
        assert!(!result.is_success());
    }

    #[tokio::test]
    async fn test_idempotency_store_error_handling() {
        let store = Arc::new(ErrorIdempotencyStore::default());
        let worker = ToolWorker::new(ExecutionConfig::default(), test_app_context())
            .with_idempotency_store(store.clone());

        let tool = Arc::new(MockTool {
            name: "test_tool".to_string(),
            should_fail: false,
        });
        worker.register_tool(tool).await;

        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "test_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: Some("test_key".to_string()),
            max_retries: 0,
            retry_count: 0,
        };

        // Should fail with idempotency store error
        let result = worker.process_job(job).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Store error"));
    }

    #[tokio::test]
    async fn test_no_idempotency_key_no_cache_check() {
        let store = Arc::new(InMemoryIdempotencyStore::new());
        let worker = ToolWorker::new(ExecutionConfig::default(), test_app_context())
            .with_idempotency_store(store.clone());

        let tool = Arc::new(MockTool {
            name: "test_tool".to_string(),
            should_fail: false,
        });
        worker.register_tool(tool).await;

        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "test_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None, // No idempotency key
            max_retries: 0,
            retry_count: 0,
        };

        // Should execute normally without cache check
        let result = worker.process_job(job).await.unwrap();
        assert!(result.is_success());
    }

    #[tokio::test]
    async fn test_no_idempotency_store_no_cache() {
        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
            ExecutionConfig::default(),
            test_app_context(),
        );
        // Don't set idempotency store

        let tool = Arc::new(MockTool {
            name: "test_tool".to_string(),
            should_fail: false,
        });
        worker.register_tool(tool).await;

        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "test_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: Some("test_key".to_string()),
            max_retries: 0,
            retry_count: 0,
        };

        // Should execute normally without cache check
        let result = worker.process_job(job).await.unwrap();
        assert!(result.is_success());
    }

    #[tokio::test]
    async fn test_cache_result_with_no_idempotency_key() {
        let store = Arc::new(InMemoryIdempotencyStore::new());
        let worker = ToolWorker::new(ExecutionConfig::default(), test_app_context())
            .with_idempotency_store(store.clone());

        let tool = Arc::new(MockTool {
            name: "test_tool".to_string(),
            should_fail: false,
        });
        worker.register_tool(tool).await;

        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "test_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None, // No idempotency key
            max_retries: 0,
            retry_count: 0,
        };

        // Should execute and not attempt to cache
        let result = worker.process_job(job).await.unwrap();
        assert!(result.is_success());
    }

    #[tokio::test]
    async fn test_cache_result_with_idempotency_disabled() {
        let config = ExecutionConfig {
            enable_idempotency: false,
            ..Default::default()
        };

        let store = Arc::new(InMemoryIdempotencyStore::new());
        let worker =
            ToolWorker::new(config, test_app_context()).with_idempotency_store(store.clone());

        let tool = Arc::new(MockTool {
            name: "test_tool".to_string(),
            should_fail: false,
        });
        worker.register_tool(tool).await;

        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "test_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: Some("test_key".to_string()),
            max_retries: 0,
            retry_count: 0,
        };

        // Should execute but not cache due to disabled idempotency
        let result = worker.process_job(job).await.unwrap();
        assert!(result.is_success());

        // Verify nothing was cached
        assert!(store.get("test_key").await.unwrap().is_none());
    }

    #[tokio::test]
    async fn test_cache_result_with_no_store() {
        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
            ExecutionConfig::default(),
            test_app_context(),
        );
        // Don't set idempotency store

        let tool = Arc::new(MockTool {
            name: "test_tool".to_string(),
            should_fail: false,
        });
        worker.register_tool(tool).await;

        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "test_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: Some("test_key".to_string()),
            max_retries: 0,
            retry_count: 0,
        };

        // Should execute but not cache due to no store
        let result = worker.process_job(job).await.unwrap();
        assert!(result.is_success());
    }

    // Tests for create_backoff_strategy and wait_with_backoff removed
    // These methods are now handled by the unified retry helper in retry.rs

    #[tokio::test]
    async fn test_acquire_semaphore_web_prefix() {
        let limits = ResourceLimits::default().with_limit("http_api", 1);

        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
            ExecutionConfig::default(),
            test_app_context(),
        )
        .with_resource_limits(limits);

        // Test web_ prefix maps to http_api
        let _permit = worker.acquire_semaphore("web_fetch").await.unwrap();
    }

    #[tokio::test]
    async fn test_acquire_semaphore_no_matching_resource() {
        let limits = ResourceLimits::default(); // Empty limits

        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
            ExecutionConfig::default(),
            test_app_context(),
        )
        .with_resource_limits(limits);

        // Should fall back to default semaphore
        let _permit = worker.acquire_semaphore("solana_test").await.unwrap();
        let _permit = worker.acquire_semaphore("random_tool").await.unwrap();
    }

    #[tokio::test]
    async fn test_run_loop_job_processing_success_logging() {
        use crate::queue::InMemoryJobQueue;

        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
            ExecutionConfig::default(),
            test_app_context(),
        );
        let tool = Arc::new(MockTool {
            name: "log_test_tool".to_string(),
            should_fail: false,
        });
        worker.register_tool(tool).await;

        let queue = Arc::new(InMemoryJobQueue::new());

        // Enqueue a successful job
        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "log_test_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None,
            max_retries: 0,
            retry_count: 0,
        };
        queue.enqueue(job).await.unwrap();

        let worker_clone = worker.clone();
        let queue_clone = queue.clone();
        let cancellation_token = tokio_util::sync::CancellationToken::new();
        let token_clone = cancellation_token.clone();

        let handle = tokio::spawn(async move { worker_clone.run(queue_clone, token_clone).await });

        // Give it time to process
        tokio::time::sleep(Duration::from_millis(50)).await;

        cancellation_token.cancel();
        handle.await.unwrap().unwrap();

        // Check that jobs_processed was incremented (line 1274)
        let metrics = worker.metrics();
        assert!(
            metrics
                .jobs_processed
                .load(std::sync::atomic::Ordering::Relaxed)
                > 0
        );
    }

    #[tokio::test]
    async fn test_run_loop_worker_error_logging() {
        use crate::queue::InMemoryJobQueue;

        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(
            ExecutionConfig::default(),
            test_app_context(),
        );
        // Don't register any tools to cause WorkerError

        let queue = Arc::new(InMemoryJobQueue::new());

        // Enqueue a job for non-existent tool
        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "nonexistent_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None,
            max_retries: 0,
            retry_count: 0,
        };
        queue.enqueue(job).await.unwrap();

        let worker_clone = worker.clone();
        let queue_clone = queue.clone();
        let cancellation_token = tokio_util::sync::CancellationToken::new();
        let token_clone = cancellation_token.clone();

        let handle = tokio::spawn(async move { worker_clone.run(queue_clone, token_clone).await });

        // Give it time to process and hit the error path
        tokio::time::sleep(Duration::from_millis(50)).await;

        cancellation_token.cancel();
        handle.await.unwrap().unwrap();
    }

    #[tokio::test]
    async fn test_semaphore_acquisition_error() {
        // This test is tricky since semaphore acquisition rarely fails
        // But we can test the error path by creating a scenario where it might
        let config = ExecutionConfig {
            max_concurrency: 1,
            ..Default::default()
        };

        let worker = ToolWorker::<InMemoryIdempotencyStore>::new(config, test_app_context());
        let tool = Arc::new(MockTool {
            name: "test_tool".to_string(),
            should_fail: false,
        });
        worker.register_tool(tool).await;

        let job = Job {
            job_id: Uuid::new_v4(),
            tool_name: "test_tool".to_string(),
            params: serde_json::json!({}),
            idempotency_key: None,
            max_retries: 0,
            retry_count: 0,
        };

        // Normal case should work
        let result = worker.process_job(job).await;
        assert!(result.is_ok());
    }

    #[test]
    fn test_tool_trait_description_method() {
        let tool = MockTool {
            name: "test".to_string(),
            should_fail: false,
        };

        // Test that description method returns expected value
        assert_eq!(tool.description(), "");
    }

    #[test]
    fn test_mock_tool_name_method() {
        let tool = MockTool {
            name: "test_name".to_string(),
            should_fail: false,
        };

        assert_eq!(tool.name(), "test_name");
    }

    #[test]
    fn test_slow_mock_tool_name_method() {
        let tool = SlowMockTool {
            name: "slow_test".to_string(),
            delay: Duration::from_millis(1),
        };

        assert_eq!(tool.name(), "slow_test");
        assert_eq!(tool.description(), "");
    }

    #[test]
    fn test_error_queue_new() {
        let _queue = ErrorQueue::default();
        // Just testing construction
    }

    #[derive(Default)]
    struct ErrorIdempotencyStore {
        _phantom: std::marker::PhantomData<()>,
    }

    #[async_trait]
    impl crate::idempotency::IdempotencyStore for ErrorIdempotencyStore {
        async fn get(&self, _key: &str) -> anyhow::Result<Option<Arc<JobResult>>> {
            Err(anyhow::anyhow!("Store error"))
        }

        async fn set(
            &self,
            _key: &str,
            _result: Arc<JobResult>,
            _ttl: Duration,
        ) -> anyhow::Result<()> {
            Err(anyhow::anyhow!("Store error"))
        }

        async fn remove(&self, _key: &str) -> anyhow::Result<()> {
            Err(anyhow::anyhow!("Store error"))
        }
    }

    struct SlowMockTool {
        name: String,
        delay: Duration,
    }

    #[async_trait]
    impl Tool for SlowMockTool {
        async fn execute(
            &self,
            _params: serde_json::Value,
            _context: &crate::provider::ApplicationContext,
        ) -> Result<JobResult, ToolError> {
            tokio::time::sleep(self.delay).await;
            Ok(JobResult::Success {
                value: serde_json::json!({"result": "slow_success"}),
                tx_hash: None,
            })
        }

        fn name(&self) -> &str {
            &self.name
        }

        fn description(&self) -> &str {
            ""
        }

        fn schema(&self) -> serde_json::Value {
            serde_json::json!({
                "type": "object",
                "additionalProperties": true
            })
        }
    }

    #[derive(Default)]
    struct ErrorQueue {
        _phantom: std::marker::PhantomData<()>,
    }

    #[async_trait]
    impl crate::queue::JobQueue for ErrorQueue {
        async fn enqueue(&self, _job: crate::jobs::Job) -> anyhow::Result<()> {
            Err(anyhow::anyhow!("Queue error"))
        }

        async fn dequeue(&self) -> anyhow::Result<Option<crate::jobs::Job>> {
            Err(anyhow::anyhow!("Dequeue error"))
        }

        async fn dequeue_with_timeout(
            &self,
            _timeout: Duration,
        ) -> anyhow::Result<Option<crate::jobs::Job>> {
            Err(anyhow::anyhow!("Dequeue timeout error"))
        }

        async fn len(&self) -> anyhow::Result<usize> {
            Err(anyhow::anyhow!("Len error"))
        }
    }
}