File size: 196,611 Bytes
d90101d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 | use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use anyhow::{Context, Result};
use colored::Colorize;
use console::style;
use convert_case::{Case, Casing};
use forge_api::{
API, AgentId, AnyProvider, ApiKeyRequest, AuthContextRequest, AuthContextResponse, ChatRequest,
ChatResponse, CodeRequest, ConfigOperation, Conversation, ConversationId, DeviceCodeRequest,
Event, InterruptionReason, ModelId, Provider, ProviderId, TextMessage, UserPrompt,
};
use forge_app::utils::{format_display_path, truncate_key};
use forge_app::{CommitResult, ToolResolver};
use forge_config::ForgeConfig;
use forge_display::MarkdownFormat;
use forge_domain::{
AuthMethod, ChatResponseContent, ConsoleWriter, ContextMessage, Role, TitleFormat, UserCommand,
};
use forge_fs::ForgeFS;
use forge_select::{ForgeWidget, SelectRow};
use forge_spinner::SpinnerManager;
use forge_tracker::ToolCallPayload;
use forge_walker::Walker;
use futures::future;
use strum::IntoEnumIterator;
use tokio_stream::StreamExt;
use url::Url;
use crate::cli::{
Cli, CommitCommandGroup, ConversationCommand, ListCommand, McpCommand, SelectCommand,
TopLevelCommand,
};
use crate::conversation_selector::ConversationSelector;
use crate::display_constants::{CommandType, headers, markers, status};
use crate::editor::ReadLineError;
use crate::error::UIError;
use crate::info::Info;
use crate::input::Console;
use crate::model::{AppCommand, ForgeCommandManager};
use crate::porcelain::Porcelain;
use crate::prompt::ForgePrompt;
use crate::state::UIState;
use crate::stream_renderer::{SharedSpinner, StreamingWriter};
use crate::sync_display::SyncProgressDisplay;
use crate::title_display::TitleDisplayExt;
use crate::tools_display::format_tools;
use crate::update::on_update;
use crate::utils::humanize_time;
use crate::zsh::ZshRPrompt;
use crate::{TRACKER, banner, tracker};
// File-specific constants
const MISSING_AGENT_TITLE: &str = "<missing agent.title>";
/// Conversation dump format used by the /dump command
#[derive(Debug, serde::Deserialize, serde::Serialize)]
struct ConversationDump {
conversation: Conversation,
related_conversations: Vec<Conversation>,
}
/// Formats an MCP server config for display, redacting sensitive information.
/// Returns the command/URL string only.
fn format_mcp_server(server: &forge_domain::McpServerConfig) -> String {
match server {
forge_domain::McpServerConfig::Stdio(stdio) => {
let mut output = format!("{} ", stdio.command);
for arg in &stdio.args {
output.push_str(&format!("{arg} "));
}
for key in stdio.env.keys() {
output.push_str(&format!("{key}=*** "));
}
output.trim().to_string()
}
forge_domain::McpServerConfig::Http(http) => http.url.clone(),
}
}
/// Formats HTTP headers for display, redacting values.
/// Returns None if there are no headers.
fn format_mcp_headers(server: &forge_domain::McpServerConfig) -> Option<String> {
match server {
forge_domain::McpServerConfig::Stdio(_) => None,
forge_domain::McpServerConfig::Http(http) => {
if http.headers.is_empty() {
None
} else {
Some(
http.headers
.keys()
.map(|k| format!("{k}=***"))
.collect::<Vec<_>>()
.join(", "),
)
}
}
}
}
pub struct UI<A: ConsoleWriter, F: Fn(ForgeConfig) -> A> {
markdown: MarkdownFormat,
state: UIState,
api: Arc<F::Output>,
new_api: Arc<F>,
console: Console,
command: Arc<ForgeCommandManager>,
cli: Cli,
spinner: SharedSpinner<A>,
config: ForgeConfig,
#[allow(dead_code)] // The guard is kept alive by being held in the struct
_guard: forge_tracker::Guard,
}
impl<A: API + ConsoleWriter + 'static, F: Fn(ForgeConfig) -> A + Send + Sync> UI<A, F> {
/// Writes a line to the console output
/// Takes anything that implements ToString trait
fn writeln<T: ToString>(&mut self, content: T) -> anyhow::Result<()> {
self.spinner.write_ln(content)
}
/// Writes a TitleFormat to the console output with proper formatting
fn writeln_title(&mut self, title: TitleFormat) -> anyhow::Result<()> {
self.spinner.write_ln(title.display())
}
fn writeln_to_stderr(&mut self, title: String) -> anyhow::Result<()> {
self.spinner.ewrite_ln(title)
}
/// Helper to get provider for an optional agent, defaulting to the current
/// active agent's provider
async fn get_provider(&self, agent_id: Option<AgentId>) -> Result<Provider<Url>> {
match agent_id {
Some(agent_id) => self.api.get_agent_provider(agent_id).await,
None => self.api.get_default_provider().await,
}
}
/// Helper to get model for an optional agent, defaulting to the current
/// active agent's model
async fn get_agent_model(&self, agent_id: Option<AgentId>) -> Option<ModelId> {
match agent_id {
Some(agent_id) => self.api.get_agent_model(agent_id).await,
None => self.api.get_session_config().await.map(|c| c.model),
}
}
fn select_raw_row(
&self,
prompt: &str,
query: Option<String>,
rows: Vec<SelectRow>,
header_lines: usize,
initial_raw: Option<String>,
) -> Result<Option<SelectRow>> {
ForgeWidget::select_rows(prompt, rows)
.query(query)
.header_lines(header_lines)
.initial_raw(initial_raw)
.prompt()
}
fn select_row_output(
&mut self,
prompt: &str,
query: Option<String>,
rows: Vec<SelectRow>,
) -> Result<()> {
if let Some(row) = self.select_raw_row(prompt, query, rows, 1, None)? {
self.writeln(row.raw)?;
}
Ok(())
}
fn porcelain_rows(porcelain: impl ToString) -> Result<Vec<SelectRow>> {
let porcelain = porcelain.to_string();
let mut lines = porcelain.lines();
let Some(header) = lines.next() else {
return Ok(Vec::new());
};
let mut rows = vec![SelectRow::header(header.to_string())];
rows.extend(lines.filter_map(|line| {
line.split_whitespace()
.next()
.map(|raw| SelectRow::new(raw.to_string(), line.to_string()))
}));
Ok(rows)
}
/// Displays banner only if user is in interactive mode.
fn display_banner(&self) -> Result<()> {
if self.cli.is_interactive() {
banner::display(false)?;
}
Ok(())
}
// Handle creating a new conversation
async fn on_new(&mut self) -> Result<()> {
let config = forge_config::ForgeConfig::read().unwrap_or_default();
self.config = config.clone();
self.api = Arc::new((self.new_api)(config));
self.init_state(false).await?;
// Set agent if provided via CLI
if let Some(agent_id) = self.cli.agent.clone() {
self.api.set_active_agent(agent_id).await?;
}
// Reset previously set CLI parameters by the user
self.cli.conversation = None;
self.cli.conversation_id = None;
self.spinner.reset();
self.display_banner()?;
self.trace_user();
self.hydrate_caches();
Ok(())
}
// Set the current mode and update conversation variable
async fn on_agent_change(&mut self, agent_id: AgentId) -> Result<()> {
// Convert string to AgentId for validation
let agent = self
.api
.get_agent_infos()
.await?
.into_iter()
.find(|info| info.id == agent_id)
.ok_or(anyhow::anyhow!("Undefined agent: {agent_id}"))?;
// Update the app config with the new operating agent.
self.api.set_active_agent(agent.id.clone()).await?;
// Update model tracking to reflect the new agent's model
let model = self.get_agent_model(Some(agent.id.clone())).await;
self.update_model(model.clone());
let name = agent.id.as_str().to_case(Case::UpperSnake).bold();
let title = format!(
"∙ {}",
agent.title.as_deref().unwrap_or(MISSING_AGENT_TITLE)
)
.dimmed();
// Show model info if agent uses a specific model
let model_info = model
.map(|m| format!(" ∙ model: {m}").dimmed().to_string())
.unwrap_or_default();
self.writeln_title(TitleFormat::action(format!("{name} {title}{model_info}")))?;
Ok(())
}
/// Initialises the UI with the provided CLI arguments and API factory.
///
/// # Arguments
/// * `cli` - Parsed command-line arguments
/// * `config` - Pre-read application configuration for the initial API
/// instance
/// * `f` - Factory closure invoked once at startup and again on each `/new`
/// command; receives the latest [`ForgeConfig`] so that config changes
/// from `forge config set` are reflected in new conversations
pub fn init(cli: Cli, config: ForgeConfig, f: F) -> Result<Self> {
// Parse CLI arguments first to get flags
let api = Arc::new(f(config.clone()));
let env = api.environment();
let command = Arc::new(ForgeCommandManager::default());
let spinner = SharedSpinner::new(SpinnerManager::new(api.clone()));
Ok(Self {
state: UIState::new(env.clone()),
api,
new_api: Arc::new(f),
console: Console::new(
env.clone(),
config.custom_history_path.clone(),
command.clone(),
),
cli,
command,
spinner,
markdown: MarkdownFormat::new(),
config,
_guard: forge_tracker::init_tracing(env.log_path(), TRACKER.clone())?,
})
}
async fn prompt(&self) -> Result<AppCommand> {
// Get usage from current conversation if available.
// Use the last message's usage for token count (context window size),
// but replace cost with the accumulated session cost so the cost
// shown reflects the total spend rather than just the last request.
let usage = if let Some(conversation_id) = &self.state.conversation_id {
self.api
.conversation(conversation_id)
.await
.ok()
.flatten()
.and_then(|conv| {
conv.usage().map(|mut u| {
u.cost = conv.accumulated_cost();
u
})
})
} else {
None
};
// Prompt the user for input
let agent_id = self.api.get_active_agent().await.unwrap_or_default();
let model = self
.get_agent_model(self.api.get_active_agent().await)
.await;
let reasoning_effort = self.api.get_reasoning_effort().await.ok().flatten();
let mut forge_prompt = ForgePrompt::new(self.state.cwd.clone(), agent_id);
if let Some(u) = usage {
forge_prompt.usage(u);
}
if let Some(m) = model {
forge_prompt.model(m);
}
if let Some(e) = reasoning_effort {
forge_prompt.reasoning_effort(e);
}
self.console.prompt(&mut forge_prompt).await
}
pub async fn run(&mut self) {
match self.run_inner().await {
Ok(_) => {}
Err(error) => {
tracing::error!(error = ?error);
// Display the full error chain for better debugging
let mut error_message = error.to_string();
let mut source = error.source();
while let Some(err) = source {
error_message.push_str(&format!("\n Caused by: {}", err));
source = err.source();
}
let _ =
self.writeln_to_stderr(TitleFormat::error(error_message).display().to_string());
}
}
}
async fn run_inner(&mut self) -> Result<()> {
if let Some(cmd) = self.cli.subcommands.clone() {
return self.handle_subcommands(cmd).await;
}
// Display the banner in dimmed colors since we're in interactive mode
self.display_banner()?;
self.init_state(true).await?;
self.trace_user();
self.hydrate_caches();
self.init_conversation().await?;
// Check for dispatch flag first
if let Some(dispatch_json) = self.cli.event.clone() {
return self.handle_dispatch(dispatch_json).await;
}
// Handle direct prompt or piped input if provided (raw text messages)
let input = self.cli.prompt.clone().or(self.cli.piped_input.clone());
if let Some(input) = input {
tracker::prompt(input.clone());
self.spinner.start(None)?;
tokio::select! {
_ = tokio::signal::ctrl_c() => {
tracing::info!("User interrupted operation with Ctrl+C");
self.spinner.reset();
return Ok(());
}
result = self.on_message(Some(input)) => {
result?;
}
}
return Ok(());
}
// Get initial input from prompt
// Prompt can fail if it doesn't have access to TTY. If it fails the first time,
// we will stop everything and bubble up the error.
let mut command = self.prompt().await;
loop {
match command {
Ok(command) => {
tokio::select! {
_ = tokio::signal::ctrl_c() => {
self.spinner.reset();
tracing::info!("User interrupted operation with Ctrl+C");
}
result = self.on_command(command) => {
match result {
Ok(exit) => if exit {return Ok(())},
Err(error) => {
if let Some(conversation_id) = self.state.conversation_id.as_ref()
&& let Some(conversation) = self.api.conversation(conversation_id).await.ok().flatten() {
TRACKER.set_conversation(conversation).await;
}
tracker::error(&error);
tracing::error!(error = ?error);
self.spinner.stop(None)?;
self.writeln_to_stderr(TitleFormat::error(format!("{error:?}")).display().to_string())?;
},
}
}
}
self.spinner.stop(None)?;
}
Err(error) => {
tracker::error(&error);
tracing::error!(error = ?error);
self.spinner.stop(None)?;
match error.downcast::<ReadLineError>() {
Ok(error) => {
Err(error)?;
}
Err(error) => self.writeln_to_stderr(
TitleFormat::error(error.to_string()).display().to_string(),
)?,
}
}
}
// Centralized prompt call at the end of the loop
command = self.prompt().await;
}
}
// Improve startup time by hydrating caches
fn hydrate_caches(&self) {
let api = self.api.clone();
tokio::spawn(async move { api.get_models().await });
let api = self.api.clone();
tokio::spawn(async move { api.get_tools().await });
let api = self.api.clone();
tokio::spawn(async move { api.get_agent_infos().await });
let api = self.api.clone();
tokio::spawn(async move {
let _ = api.hydrate_channel();
});
}
async fn handle_generate_conversation_id(&mut self) -> Result<()> {
let conversation_id = forge_domain::ConversationId::generate();
println!("{}", conversation_id.into_string());
Ok(())
}
async fn handle_subcommands(&mut self, subcommand: TopLevelCommand) -> anyhow::Result<()> {
match subcommand {
TopLevelCommand::Agent(agent_group) => {
match agent_group.command {
crate::cli::AgentCommand::List => {
self.on_show_agents(agent_group.porcelain, false).await?;
}
}
return Ok(());
}
TopLevelCommand::List(list_group) => {
let porcelain = list_group.porcelain;
match list_group.command {
ListCommand::Agent { custom } => {
self.on_show_agents(porcelain, custom).await?;
}
ListCommand::Provider { types } => {
self.on_show_providers(porcelain, types).await?;
}
ListCommand::Model => {
self.on_show_models(porcelain).await?;
}
ListCommand::Command { custom } => {
if custom {
self.on_show_custom_commands(porcelain).await?;
} else {
self.on_show_commands(porcelain).await?;
}
}
ListCommand::Config => {
self.on_show_config(porcelain).await?;
}
ListCommand::Tool { agent } => {
self.on_show_tools(agent, porcelain).await?;
}
ListCommand::Mcp => {
self.on_show_mcp_servers(porcelain).await?;
}
ListCommand::Conversation { parent } => {
if let Some(parent_id) = parent {
let parent_conv = self.validate_conversation_exists(&parent_id).await?;
let children = self.fetch_related_conversations(&parent_conv).await;
if children.is_empty() {
self.writeln_title(TitleFormat::info(
"No child conversations found.",
))?;
} else {
let mut info = Info::new();
for conv in children.into_iter() {
let title = conv
.title
.as_deref()
.map(|t| t.to_string())
.unwrap_or_else(|| markers::EMPTY.to_string());
let duration = chrono::Utc::now().signed_duration_since(
conv.metadata
.updated_at
.unwrap_or(conv.metadata.created_at),
);
let duration = std::time::Duration::from_secs(
(duration.num_minutes() * 60).max(0) as u64,
);
let time_ago = if duration.is_zero() {
"now".to_string()
} else {
format!("{} ago", humantime::format_duration(duration))
};
info = info
.add_title(conv.id)
.add_key_value("Title", title)
.add_key_value("Updated", time_ago);
}
let porcelain = Porcelain::from(&info)
.drop_col(3)
.truncate(1, 60)
.uppercase_headers();
self.writeln(porcelain)?;
}
} else {
self.on_show_conversations(porcelain).await?;
}
}
ListCommand::Cmd => {
self.on_show_custom_commands(porcelain).await?;
}
ListCommand::Skill { custom } => {
self.on_show_skills(porcelain, custom).await?;
}
ListCommand::File => {
self.on_list_files(porcelain).await?;
}
}
return Ok(());
}
TopLevelCommand::Zsh(terminal_group) => {
match terminal_group {
crate::cli::ZshCommandGroup::Plugin => {
self.on_zsh_plugin().await?;
}
crate::cli::ZshCommandGroup::Theme => {
self.on_zsh_theme().await?;
}
crate::cli::ZshCommandGroup::Doctor => {
self.on_zsh_doctor().await?;
}
crate::cli::ZshCommandGroup::Rprompt => {
if let Some(text) = self.handle_zsh_rprompt_command().await {
print!("{}", text)
}
return Ok(());
}
crate::cli::ZshCommandGroup::Setup => {
self.on_zsh_setup().await?;
}
crate::cli::ZshCommandGroup::Keyboard => {
self.on_zsh_keyboard().await?;
}
crate::cli::ZshCommandGroup::Format { buffer } => {
print!("{}", crate::zsh::paste::wrap_pasted_text(&buffer));
return Ok(());
}
}
return Ok(());
}
TopLevelCommand::Mcp(mcp_command) => match mcp_command.command {
McpCommand::Import(import_args) => {
let scope: forge_domain::Scope = import_args.scope.into();
// Parse the incoming MCP configuration
let incoming_config: forge_domain::McpConfig = serde_json::from_str(&import_args.json)
.context("Failed to parse MCP configuration JSON. Expected format: {\"mcpServers\": {...}}")?;
// Read only the scope-specific config (not merged)
let mut scope_config = self.api.read_mcp_config(Some(&scope)).await?;
// Merge the incoming servers with scope-specific config only
let mut added_servers = Vec::new();
for (server_name, server_config) in incoming_config.mcp_servers {
scope_config
.mcp_servers
.insert(server_name.clone(), server_config);
added_servers.push(server_name);
}
// Write back to the specific scope only
self.api.write_mcp_config(&scope, &scope_config).await?;
// Log each added server after successful write
for server_name in added_servers {
self.writeln_title(TitleFormat::info(format!(
"Added MCP server '{server_name}'"
)))?;
}
}
McpCommand::List => {
self.on_show_mcp_servers(mcp_command.porcelain).await?;
}
McpCommand::Remove(rm) => {
let name = forge_api::ServerName::from(rm.name);
let scope: forge_domain::Scope = rm.scope.into();
// Read only the scope-specific config (not merged)
let mut scope_config = self.api.read_mcp_config(Some(&scope)).await?;
// Remove the server from scope-specific config only
scope_config.mcp_servers.remove(&name);
// Write back to the specific scope only
self.api.write_mcp_config(&scope, &scope_config).await?;
self.writeln_title(TitleFormat::info(format!("Removed server: {name}")))?;
}
McpCommand::Show(val) => {
let name = forge_api::ServerName::from(val.name);
let config = self.api.read_mcp_config(None).await?;
let server = config
.mcp_servers
.get(&name)
.ok_or(anyhow::anyhow!("Server not found"))?;
// Get MCP servers to check for failures
let tools = self.api.get_tools().await?;
// Display server configuration
self.writeln_title(TitleFormat::info(format!(
"{name}: {}",
format_mcp_server(server)
)))?;
// Display error if the server failed to initialize
if let Some(error) = tools.mcp.get_failures().get(&name) {
self.writeln_title(TitleFormat::error(error))?;
}
}
McpCommand::Reload => {
self.spinner.start(Some("Reloading MCPs"))?;
self.api.reload_mcp().await?;
self.writeln_title(TitleFormat::info("MCP reloaded"))?;
}
McpCommand::Login(args) => {
self.handle_mcp_login(&args.name).await?;
}
McpCommand::Logout(args) => {
self.handle_mcp_logout(&args.name).await?;
}
},
TopLevelCommand::Info { porcelain, conversation_id } => {
// Only initialize state (agent/provider/model resolution).
// Avoid on_new() which also spawns fire-and-forget background
// tasks via hydrate_caches() that race with process exit and
// cause "JoinHandle polled after completion" panics.
self.init_state(false).await?;
self.on_info(porcelain, conversation_id).await?;
return Ok(());
}
TopLevelCommand::Banner => {
banner::display(true)?;
return Ok(());
}
TopLevelCommand::Config(config_group) => {
self.handle_config_command(config_group.command.clone(), config_group.porcelain)
.await?;
return Ok(());
}
TopLevelCommand::Provider(provider_group) => {
self.handle_provider_command(provider_group).await?;
return Ok(());
}
TopLevelCommand::Conversation(conversation_group) => {
self.handle_conversation_command(conversation_group).await?;
return Ok(());
}
TopLevelCommand::Suggest { prompt } => {
self.on_cmd(UserPrompt::from(prompt)).await?;
return Ok(());
}
TopLevelCommand::Cmd(run_group) => {
let porcelain = run_group.porcelain;
match run_group.command {
crate::cli::CmdCommand::List { custom } => {
if custom {
self.on_show_custom_commands(porcelain).await?;
} else {
self.on_show_commands(porcelain).await?;
}
}
crate::cli::CmdCommand::Execute { commands: args } => {
// Execute the custom command
self.init_state(false).await?;
// If conversation_id is provided, set it in CLI before initializing
if let Some(ref cid) = run_group.conversation_id {
self.cli.conversation_id = Some(*cid);
}
self.init_conversation().await?;
self.spinner.start(None)?;
// Join all args into a single command string
let command_str = args.join(" ");
// Add slash prefix if not present
let command_with_slash = if command_str.starts_with('/') {
command_str
} else {
format!("/{command_str}")
};
let command = self.command.parse(&command_with_slash)?;
self.on_command(command).await?;
}
}
return Ok(());
}
TopLevelCommand::Workspace(index_group) => {
match index_group.command {
crate::cli::WorkspaceCommand::Sync { path, init } => {
self.on_index(path, init).await?;
}
crate::cli::WorkspaceCommand::List { porcelain } => {
self.on_list_workspaces(porcelain).await?;
}
crate::cli::WorkspaceCommand::Query {
query,
path,
limit,
top_k,
use_case,
starts_with,
ends_with,
} => {
let mut params =
forge_domain::SearchParams::new(&query, &use_case).limit(limit);
if let Some(k) = top_k {
params = params.top_k(k);
}
if let Some(prefix) = starts_with {
params = params.starts_with(prefix);
}
if let Some(suffix) = ends_with {
params = params.ends_with(vec![suffix]);
}
self.on_query(path, params).await?;
}
crate::cli::WorkspaceCommand::Info { path } => {
self.on_workspace_info(path).await?;
}
crate::cli::WorkspaceCommand::Delete { workspace_ids } => {
self.on_delete_workspaces(workspace_ids).await?;
}
crate::cli::WorkspaceCommand::Status { path, porcelain } => {
self.on_workspace_status(path, porcelain).await?;
}
crate::cli::WorkspaceCommand::Init { path, yes } => {
self.on_workspace_init(path, yes).await?;
}
}
return Ok(());
}
TopLevelCommand::Commit(commit_group) => {
self.init_state(false).await?;
let preview = commit_group.preview;
let result = self.handle_commit_command(commit_group).await?;
if preview {
self.writeln(&result.message)?;
} else if !result.git_output.is_empty() {
self.writeln_to_stderr(result.git_output.trim_end().to_string())?;
} else {
self.writeln_to_stderr(result.message.trim_end().to_string())?;
}
return Ok(());
}
TopLevelCommand::Data(data_command_group) => {
let mut stream = self.api.generate_data(data_command_group.into()).await?;
while let Some(data) = stream.next().await {
self.writeln(data?)?;
}
}
TopLevelCommand::Vscode(vscode_command) => {
match vscode_command {
crate::cli::VscodeCommand::InstallExtension => {
self.on_vscode_extension_install().await?;
}
}
return Ok(());
}
TopLevelCommand::Update(args) => {
let update = forge_config::Update::default().auto_update(args.no_confirm);
on_update(self.api.clone(), Some(&update)).await;
return Ok(());
}
TopLevelCommand::Setup => {
self.on_zsh_setup().await?;
return Ok(());
}
TopLevelCommand::Doctor => {
self.on_zsh_doctor().await?;
return Ok(());
}
TopLevelCommand::Logs(args) => {
let log_dir = self.api.environment().log_path();
crate::logs::run(args, log_dir).await?;
return Ok(());
}
TopLevelCommand::Select(cmd) => {
if !matches!(&cmd.command, SelectCommand::File { .. }) {
self.init_state(false).await?;
}
match &cmd.command {
SelectCommand::File { query } => {
if let Some(file) =
crate::completer::select_workspace_file(&self.state.cwd, query.clone())?
{
self.writeln(file)?;
}
}
SelectCommand::Model { query } => {
if let Some((model_id, provider_id)) =
self.select_model(None, query.clone()).await?
{
self.writeln(model_id.as_str())?;
self.writeln(provider_id.as_ref())?;
}
}
SelectCommand::Agent { query } => {
if let Some(agent_id) = self.select_agent(query.clone()).await? {
self.writeln(agent_id.as_str())?;
}
}
SelectCommand::Provider { query, configured } => {
if let Some(provider) =
self.select_provider(query.clone(), *configured).await?
{
self.writeln(provider.id().as_ref())?;
}
}
SelectCommand::ReasoningEffort { query } => {
if let Some(effort) = self
.select_reasoning_effort("Reasoning Effort", query.clone())
.await?
{
self.writeln(effort)?;
}
}
SelectCommand::Command { query } => {
let rows = Self::porcelain_rows(self.commands_porcelain().await?)?;
if !rows.is_empty() {
self.select_row_output("Command", query.clone(), rows)?;
}
}
SelectCommand::Conversation { query, parent } => {
let conversations = if let Some(parent_id) = parent {
let parent_conv = self.validate_conversation_exists(parent_id).await?;
self.fetch_related_conversations(&parent_conv).await
} else {
let max_conversations = self.config.max_conversations;
let conversations =
self.api.get_conversations(Some(max_conversations)).await?;
Self::user_initiated_conversations(conversations)
};
if !conversations.is_empty()
&& let Some(conversation) = ConversationSelector::select_conversation(
&conversations,
self.state.conversation_id,
query.clone(),
)
.await?
{
self.writeln(conversation.id)?;
}
}
}
return Ok(());
}
}
Ok(())
}
async fn handle_conversation_command(
&mut self,
conversation_group: crate::cli::ConversationCommandGroup,
) -> anyhow::Result<()> {
match conversation_group.command {
ConversationCommand::List { porcelain } => {
self.on_show_conversations(porcelain).await?;
}
ConversationCommand::New => {
self.handle_generate_conversation_id().await?;
}
ConversationCommand::Dump { id, html } => {
self.validate_conversation_exists(&id).await?;
let original_id = self.state.conversation_id;
self.state.conversation_id = Some(id);
self.spinner.start(Some("Dumping"))?;
self.on_dump(html).await?;
self.state.conversation_id = original_id;
}
ConversationCommand::Compact { id } => {
self.validate_conversation_exists(&id).await?;
let original_id = self.state.conversation_id;
self.state.conversation_id = Some(id);
self.spinner.start(Some("Compacting"))?;
self.on_compaction().await?;
self.state.conversation_id = original_id;
}
ConversationCommand::Delete { id } => {
let conversation_id =
ConversationId::parse(&id).context(format!("Invalid conversation ID: {id}"))?;
self.validate_conversation_exists(&conversation_id).await?;
self.on_conversation_delete(conversation_id).await?;
}
ConversationCommand::Retry { id } => {
self.validate_conversation_exists(&id).await?;
let original_id = self.state.conversation_id;
self.state.conversation_id = Some(id);
self.spinner.start(None)?;
self.on_message(None).await?;
self.state.conversation_id = original_id;
}
ConversationCommand::Resume { id } => {
self.validate_conversation_exists(&id).await?;
self.state.conversation_id = Some(id);
self.writeln_title(TitleFormat::info(format!("Resumed conversation: {id}")))?;
// Interactive mode will be handled by the main loop
}
ConversationCommand::Show { id, md } => {
let conversation = self.validate_conversation_exists(&id).await?;
self.on_show_last_message(conversation, md).await?;
}
ConversationCommand::Info { id } => {
let conversation = self.validate_conversation_exists(&id).await?;
self.on_show_conv_info(conversation).await?;
}
ConversationCommand::Stats { id, porcelain } => {
let conversation = self.validate_conversation_exists(&id).await?;
self.on_show_conv_stats(conversation, porcelain).await?;
}
ConversationCommand::Clone { id, porcelain } => {
let conversation = self.validate_conversation_exists(&id).await?;
self.spinner.start(Some("Cloning"))?;
self.on_clone_conversation(conversation, porcelain).await?;
self.spinner.stop(None)?;
}
ConversationCommand::Rename { id, name } => {
self.validate_conversation_exists(&id).await?;
let name = name.trim().to_string();
if name.is_empty() {
return Err(anyhow::anyhow!(
"Please provide a name for the conversation."
));
}
self.api.rename_conversation(&id, name.clone()).await?;
self.writeln_title(TitleFormat::info(format!(
"Conversation renamed to '{}'",
name.bold()
)))?;
}
}
Ok(())
}
async fn validate_conversation_exists(
&self,
conversation_id: &ConversationId,
) -> anyhow::Result<Conversation> {
let conversation = self.api.conversation(conversation_id).await?;
conversation.ok_or_else(|| anyhow::anyhow!("Conversation '{conversation_id}' not found"))
}
async fn on_conversation_delete(
&mut self,
conversation_id: ConversationId,
) -> anyhow::Result<()> {
self.spinner.start(Some("Deleting conversation"))?;
self.api.delete_conversation(&conversation_id).await?;
self.spinner.stop(None)?;
self.writeln_title(TitleFormat::debug(format!(
"Successfully deleted conversation '{}'",
conversation_id
)))?;
Ok(())
}
/// Handle `mcp login <name>` command.
///
/// Triggers the OAuth authentication flow for the specified MCP server.
/// Uses the API layer which delegates to rmcp's OAuth state machine
/// for metadata discovery, dynamic registration, PKCE, and token exchange.
async fn handle_mcp_login(&mut self, name: &str) -> anyhow::Result<()> {
let server_name = forge_api::ServerName::from(name.to_string());
let config = self.api.read_mcp_config(None).await?;
let server = config.mcp_servers.get(&server_name);
match server {
Some(forge_domain::McpServerConfig::Http(http)) => {
// Check auth status first
let status = self.api.mcp_auth_status(&http.url).await?;
if status == "authenticated" {
self.writeln_title(TitleFormat::info(
format!("MCP server '{}' is already authenticated. Use 'mcp logout {}' first to re-authenticate.", name, name)
))?;
return Ok(());
}
// Force re-auth by removing any stale credentials
let _ = self.api.mcp_logout(Some(&http.url)).await;
// Run the OAuth flow (opens browser, waits for callback)
match self.api.mcp_auth(&http.url).await {
Ok(()) => {
self.writeln_title(TitleFormat::info(format!(
"Successfully authenticated with MCP server '{}'",
name
)))?;
// Reload MCP to reconnect with new credentials
self.spinner.start(Some("Reloading MCPs"))?;
match self.api.reload_mcp().await {
Ok(()) => {
self.writeln_title(TitleFormat::info("MCP reloaded"))?;
}
Err(e) => {
self.writeln_title(TitleFormat::error(format!(
"MCP reload failed: {}",
e
)))?;
}
}
}
Err(e) => {
self.writeln_title(TitleFormat::error(format!(
"Authentication with MCP server '{}' failed: {}",
name, e
)))?;
}
}
}
Some(_) => {
self.writeln_title(TitleFormat::error(format!(
"MCP server '{}' is not an HTTP server (OAuth only applies to HTTP servers)",
name
)))?;
}
None => {
self.writeln_title(TitleFormat::error(format!(
"MCP server '{}' not found. Use 'mcp list' to see available servers.",
name
)))?;
}
}
Ok(())
}
/// Handle `mcp logout <name>` command.
///
/// Removes stored OAuth credentials for the specified MCP server
/// or all servers if "all" is specified.
/// Automatically reloads MCPs after logout to reflect auth state change.
async fn handle_mcp_logout(&mut self, name: &str) -> anyhow::Result<()> {
if name == "all" {
self.api.mcp_logout(None).await?;
self.writeln_title(TitleFormat::info("Removed all MCP OAuth credentials"))?;
} else {
let server_name = forge_api::ServerName::from(name.to_string());
let config = self.api.read_mcp_config(None).await?;
let server = config.mcp_servers.get(&server_name);
match server {
Some(forge_domain::McpServerConfig::Http(http)) => {
self.api.mcp_logout(Some(&http.url)).await?;
self.writeln_title(TitleFormat::info(format!(
"Removed OAuth credentials for MCP server '{}'",
name
)))?;
}
Some(_) => {
self.writeln_title(TitleFormat::error(format!(
"MCP server '{}' is not an HTTP server",
name
)))?;
return Ok(());
}
None => {
self.writeln_title(TitleFormat::error(format!(
"MCP server '{}' not found. Use 'mcp list' to see available servers.",
name
)))?;
return Ok(());
}
}
}
// Reload MCPs to reflect auth state change
self.spinner.start(Some("Reloading MCPs"))?;
self.api.reload_mcp().await?;
self.writeln_title(TitleFormat::info("MCP reloaded"))?;
Ok(())
}
async fn handle_provider_command(
&mut self,
provider_group: crate::cli::ProviderCommandGroup,
) -> anyhow::Result<()> {
use crate::cli::ProviderCommand;
match provider_group.command {
ProviderCommand::Login { provider } => {
self.handle_provider_login(provider.as_ref()).await?;
}
ProviderCommand::Logout { provider } => {
self.handle_provider_logout(provider.as_ref()).await?;
}
ProviderCommand::List { types } => {
self.on_show_providers(provider_group.porcelain, types)
.await?;
}
}
Ok(())
}
async fn handle_provider_login(
&mut self,
provider_id: Option<&ProviderId>,
) -> anyhow::Result<()> {
// Get the provider to login to
let any_provider = if let Some(id) = provider_id {
// Specific provider requested
self.api.get_provider(id).await?
} else {
// Fetch all providers for selection (no type filter, like shell :login)
let providers = self.api.get_providers().await?;
match self.select_provider_from_list(providers, "Provider", None, None)? {
Some(provider) => provider,
None => {
self.writeln_title(TitleFormat::info("Cancelled"))?;
return Ok(());
}
}
};
// For login, always configure (even if already configured) to allow
// re-authentication
let provider = match self
.configure_provider(any_provider.id(), any_provider.auth_methods().to_vec())
.await?
{
Some(provider) => provider,
None => return Ok(()),
};
// Set as default and handle model selection
self.finalize_provider_activation(provider, None).await
}
async fn handle_provider_logout(
&mut self,
provider_id: Option<&ProviderId>,
) -> anyhow::Result<bool> {
// If provider_id is specified, logout from that specific provider
if let Some(id) = provider_id {
let provider = self.api.get_provider(id).await?;
if !provider.is_configured() {
return Err(anyhow::anyhow!("Provider '{id}' is not configured"));
}
self.api.remove_provider(id).await?;
self.writeln_title(TitleFormat::debug(format!(
"Successfully logged out from {id}"
)))?;
return Ok(true);
}
// Fetch and filter configured providers (like shell :logout filters to status
// [yes])
let configured_providers: Vec<AnyProvider> = self
.api
.get_providers()
.await?
.into_iter()
.filter(|p| p.is_configured())
.collect();
if configured_providers.is_empty() {
self.writeln_title(TitleFormat::info("No configured providers found"))?;
return Ok(false);
}
match self.select_provider_from_list(configured_providers, "Provider", None, None)? {
Some(provider) => {
let provider_id = provider.id();
self.api.remove_provider(&provider_id).await?;
self.writeln_title(TitleFormat::debug(format!(
"Successfully logged out from {provider_id}"
)))?;
return Ok(true);
}
None => {
self.writeln_title(TitleFormat::info("Cancelled"))?;
}
}
Ok(false)
}
async fn handle_commit_command(
&mut self,
commit_group: CommitCommandGroup,
) -> anyhow::Result<CommitResult> {
self.spinner.start(Some("Creating commit"))?;
// Convert Vec<String> to Option<String> by joining with spaces
let additional_context = if commit_group.text.is_empty() {
None
} else {
Some(commit_group.text.join(" "))
};
// Handle the commit command
let result = self
.api
.commit(
commit_group.preview,
commit_group.max_diff_size,
commit_group.diff,
additional_context,
)
.await;
match result {
Ok(result) => {
self.spinner.stop(None)?;
Ok(result)
}
Err(e) => {
self.spinner.stop(None)?;
Err(e)
}
}
}
/// Builds an Info structure for agents with their details
async fn build_agents_info(&self, custom: bool) -> anyhow::Result<Info> {
let mut agents = self.api.get_agents().await?;
// Sort agents alphabetically by ID
agents.sort_by(|a, b| a.id.as_str().cmp(b.id.as_str()));
// Filter agents based on custom flag
if custom {
agents.retain(|agent| agent.path.is_some());
}
let mut info = Info::new();
for agent in agents.iter() {
let id = agent.id.as_str().to_string();
let title = agent
.title
.as_deref()
.map(|title| title.lines().collect::<Vec<_>>().join(" "));
// Get provider and model for this agent
let provider_name = match self.get_provider(Some(agent.id.clone())).await {
Ok(p) => p.id.to_string(),
Err(e) => format!("Error: [{}]", e),
};
let model_name = agent.model.as_str().to_string();
let reasoning = if agent
.reasoning
.as_ref()
.and_then(|a| a.enabled)
.unwrap_or_default()
{
status::YES
} else {
status::NO
};
let location = agent
.path
.as_ref()
.map(|s| s.to_string())
.unwrap_or_else(|| markers::BUILT_IN.to_string());
info = info
.add_title(id.to_case(Case::UpperSnake))
.add_key_value("Id", id)
.add_key_value("Title", title)
.add_key_value("Location", location)
.add_key_value("Provider", provider_name)
.add_key_value("Model", model_name)
.add_key_value("Reasoning Enabled", reasoning);
}
Ok(info)
}
async fn on_show_agents(&mut self, porcelain: bool, custom: bool) -> anyhow::Result<()> {
let agents = self.api.get_agent_infos().await?;
if agents.is_empty() {
return Ok(());
}
let info = self.build_agents_info(custom).await?;
if porcelain {
let porcelain = Porcelain::from(&info)
.drop_col(0)
.truncate(3, 60)
.uppercase_headers();
self.writeln(porcelain)?;
} else {
self.writeln(info)?;
}
Ok(())
}
/// Lists all the providers
async fn on_show_providers(
&mut self,
porcelain: bool,
types: Vec<forge_domain::ProviderType>,
) -> anyhow::Result<()> {
let mut providers = self.api.get_providers().await?;
// Filter by type if specified
if !types.is_empty() {
providers.retain(|p| types.contains(p.provider_type()));
}
if providers.is_empty() {
return Ok(());
}
let mut info = Info::new();
for provider in providers.iter() {
let id: &str = &provider.id();
let display_name = provider.id().to_string();
let domain = if let Some(url) = provider.url() {
url.domain().map(|d| d.to_string()).unwrap_or_default()
} else {
markers::EMPTY.to_string()
};
let configured = provider.is_configured();
info = info
.add_title(id.to_case(Case::UpperSnake))
.add_key_value("name", display_name)
.add_key_value("id", id)
.add_key_value("host", domain);
if configured {
info = info.add_key_value("logged in", status::YES);
};
}
if porcelain {
let porcelain = Porcelain::from(&info).drop_col(0).uppercase_headers();
self.writeln(porcelain)?;
} else {
self.writeln(info)?;
}
Ok(())
}
/// Lists all the models
async fn on_show_models(&mut self, porcelain: bool) -> anyhow::Result<()> {
self.spinner.start(Some("Fetching Models"))?;
let mut all_provider_models = match self.api.get_all_provider_models().await {
Ok(provider_models) => provider_models,
Err(err) => {
self.spinner.stop(None)?;
return Err(err);
}
};
if all_provider_models.is_empty() {
return Ok(());
}
// Sort models and then providers
all_provider_models
.iter_mut()
.for_each(|pm| pm.models.sort_by(|a, b| a.id.as_str().cmp(b.id.as_str())));
all_provider_models.sort_by(|a, b| a.provider_id.as_ref().cmp(b.provider_id.as_ref()));
let mut info = Info::new();
for pm in &all_provider_models {
let provider_id: &str = &pm.provider_id;
let provider_display = pm.provider_id.to_string();
for model in &pm.models {
let id = model.id.to_string();
info = info
.add_title(&id)
.add_key_value("Model", model.name.as_ref().unwrap_or(&id))
.add_key_value("Provider", &provider_display)
.add_key_value("Provider Id", provider_id);
// Add context length if available, otherwise use "unknown"
if let Some(limit) = model.context_length {
let context = if limit >= 1_000_000 {
format!("{}M", limit / 1_000_000)
} else if limit >= 1000 {
format!("{}k", limit / 1000)
} else {
format!("{limit}")
};
info = info.add_key_value("Context Window", context);
} else {
info = info.add_key_value("Context Window", markers::EMPTY)
}
// Add tools support indicator if explicitly supported
if let Some(supported) = model.tools_supported {
info = info.add_key_value(
"Tool Supported",
if supported { status::YES } else { status::NO },
)
} else {
info = info.add_key_value("Tools", markers::EMPTY)
}
// Add image modality support indicator
let supports_image = model
.input_modalities
.contains(&forge_domain::InputModality::Image);
info = info.add_key_value(
"Image",
if supports_image {
status::YES
} else {
status::NO
},
);
}
}
if porcelain {
self.writeln(Porcelain::from(&info).truncate(1, 40).uppercase_headers())?;
} else {
self.writeln(info)?;
}
Ok(())
}
async fn commands_porcelain(&self) -> Result<Porcelain> {
let custom_commands = self.api.get_commands().await?;
let mut info = Info::new();
for cmd in AppCommand::iter().filter(|c| !c.is_internal() && !c.is_agent_switch()) {
info = info
.add_title(cmd.name())
.add_key_value("type", CommandType::Command)
.add_key_value("description", cmd.usage());
}
info = info
.add_title("ask")
.add_key_value("type", CommandType::Agent)
.add_key_value(
"description",
"Research and investigation agent [alias for: sage]",
)
.add_title("plan")
.add_key_value("type", CommandType::Agent)
.add_key_value(
"description",
"Planning and strategy agent [alias for: muse]",
);
let agent_infos = self.api.get_agent_infos().await?;
for agent_info in agent_infos {
let title = agent_info
.title
.map(|title| title.lines().collect::<Vec<_>>().join(" "));
info = info
.add_title(agent_info.id.to_string())
.add_key_value("type", CommandType::Agent)
.add_key_value("description", title);
}
for command in custom_commands {
info = info
.add_title(command.name.clone())
.add_key_value("type", CommandType::Custom)
.add_key_value("description", command.description.clone());
}
Ok(Porcelain::from(&info)
.uppercase_headers()
.sort_by(&[1, 0])
.to_case(&[1], Case::UpperSnake)
.map_col(0, |col| {
if col.as_deref() == Some(headers::ID) {
Some("COMMAND".to_string())
} else {
col
}
}))
}
/// Lists all the commands
async fn on_show_commands(&mut self, porcelain: bool) -> anyhow::Result<()> {
let custom_commands = self.api.get_commands().await?;
if porcelain {
self.writeln(self.commands_porcelain().await?)?;
} else {
// Non-porcelain: render in the same flat format as :help in the REPL.
let command_manager = ForgeCommandManager::default();
command_manager.register_all(custom_commands);
let info = Info::from(&command_manager);
self.writeln(info)?;
}
Ok(())
}
/// Lists only custom commands (used by `forge run`)
async fn on_show_custom_commands(&mut self, porcelain: bool) -> anyhow::Result<()> {
let custom_commands = self.api.get_commands().await?;
let mut info = Info::new();
for command in custom_commands {
info = info
.add_title(command.name.clone())
.add_key_value("description", command.description.clone());
}
if porcelain {
let porcelain = Porcelain::from(&info).uppercase_headers();
self.writeln(porcelain)?;
} else {
self.writeln(info)?;
}
Ok(())
}
/// Lists available skills
async fn on_show_skills(&mut self, porcelain: bool, custom: bool) -> anyhow::Result<()> {
let skills = self.api.get_skills().await?;
// Filter skills based on custom flag
let skills = if custom {
skills
.into_iter()
.filter(|skill| skill.path.is_some())
.collect()
} else {
skills
};
let mut info = Info::new();
let env = self.api.environment();
for skill in skills {
info = info
.add_title(skill.name.clone().to_case(Case::Sentence).to_uppercase())
.add_key_value("name", skill.name);
if let Some(path) = skill.path {
info = info.add_key_value("path", format_display_path(&path, &env.cwd));
}
info = info.add_key_value("description", skill.description);
}
if porcelain {
let porcelain = Porcelain::from(&info)
.drop_col(0)
.truncate(2, 60)
.uppercase_headers();
self.writeln(porcelain)?;
} else {
self.writeln(info)?;
}
Ok(())
}
/// Lists files and directories in the current workspace.
///
/// Uses the same `Walker::max_all()` configuration as the REPL file picker
/// and the shell plugin (`fd --type f --type d --hidden --exclude .git`):
/// hidden files included, respects `.gitignore`, directories suffixed with
/// `/`.
async fn on_list_files(&mut self, porcelain: bool) -> anyhow::Result<()> {
let env = self.api.environment();
let files = Walker::max_all()
.cwd(env.cwd.clone())
.get()
.await
.context("Failed to walk workspace files")?;
if porcelain {
for file in files {
self.writeln(file.path)?;
}
} else {
let mut info = Info::new();
for file in &files {
info = info.add_key_value("path", file.path.clone());
}
self.writeln(info)?;
}
Ok(())
}
/// Lists current configuration values
async fn on_show_config(&mut self, porcelain: bool) -> anyhow::Result<()> {
// Get the effective resolved config
let config = &self.config;
// Serialize to TOML pretty format
let config_toml = toml_edit::ser::to_string_pretty(config)
.map_err(|e| anyhow::anyhow!("Failed to serialize config: {}", e))?;
if porcelain {
// For porcelain mode, output raw TOML without highlighting
self.writeln(config_toml)?;
} else {
// For human-readable mode, add a title and syntax-highlight the TOML
self.writeln("\nCONFIGURATION\n".bold().dimmed())?;
let highlighted =
forge_display::SyntaxHighlighter::default().highlight(&config_toml, "toml");
self.writeln(highlighted)?;
}
Ok(())
}
/// Displays available tools for the current agent
async fn on_show_tools(&mut self, agent_id: AgentId, porcelain: bool) -> anyhow::Result<()> {
self.spinner.start(Some("Loading"))?;
let all_tools = self.api.get_tools().await?;
let agents = self.api.get_agents().await?;
let agent = agents.into_iter().find(|agent| agent.id == agent_id);
let agent_tools = if let Some(agent) = agent {
let resolver = ToolResolver::new(all_tools.clone().into());
resolver
.resolve(&agent)
.into_iter()
.map(|def| def.name.clone())
.collect()
} else {
Vec::new()
};
let info = format_tools(&agent_tools, &all_tools);
if porcelain {
self.writeln(
Porcelain::from(&info)
.into_long()
.drop_col(1)
.uppercase_headers(),
)?;
} else {
self.writeln(info)?;
}
Ok(())
}
/// Displays all MCP servers with their available tools
async fn on_show_mcp_servers(&mut self, porcelain: bool) -> anyhow::Result<()> {
self.spinner.start(Some("Loading MCP servers"))?;
let mcp_servers = self.api.read_mcp_config(None).await?;
let all_tools = self.api.get_tools().await?;
let mut info = Info::new();
for (name, server) in mcp_servers.mcp_servers {
let label = match server {
forge_domain::McpServerConfig::Stdio(_) => "Command",
forge_domain::McpServerConfig::Http(_) => "URL",
};
info = info
.add_title(name.to_uppercase())
.add_key_value("Type", server.server_type())
.add_key_value(label, format_mcp_server(&server));
// Add headers for HTTP servers if present
if let Some(headers) = format_mcp_headers(&server) {
info = info.add_key_value("Headers", headers);
}
if server.is_disabled() {
info = info.add_key_value("Status", status::NO);
}
// Add tools for this MCP server
if let Some(tools) = all_tools.mcp.get_servers().get(&name)
&& !tools.is_empty()
{
info = info.add_key_value("Tools", tools.len().to_string());
for tool in tools {
info = info.add_value(tool.name.to_string());
}
}
}
if porcelain {
self.writeln(Porcelain::from(&info).uppercase_headers().truncate(3, 60))?;
} else {
self.writeln(info)?;
}
// Show failed MCP servers
if !porcelain && !all_tools.mcp.get_failures().is_empty() {
self.writeln("MCP FAILURES\n".dimmed().bold())?;
for error in all_tools.mcp.get_failures().values() {
let error = style(error).red();
self.writeln(error)?;
}
}
Ok(())
}
async fn on_info(
&mut self,
porcelain: bool,
conversation_id: Option<ConversationId>,
) -> anyhow::Result<()> {
let mut info = Info::new();
// Fetch conversation
let conversation = match conversation_id {
Some(conversation_id) => self.api.conversation(&conversation_id).await.ok().flatten(),
None => None,
};
// Fetch agent
let agent = self.api.get_active_agent().await;
// Fetch model (resolved with default model if unset)
let model = self.get_agent_model(agent.clone()).await;
// Fetch agent-specific provider or default provider if unset
let agent_provider = self.get_provider(agent.clone()).await.ok();
// Fetch default provider (could be different from the set provider)
let default_provider = self.api.get_default_provider().await.ok();
// Add agent information
info = info.add_title("AGENT");
if let Some(agent) = agent {
info = info.add_key_value("ID", agent.as_str().to_uppercase());
}
// Add model information if available
if let Some(model) = model {
info = info.add_key_value("Model", model.as_str());
}
// Add provider information
match (default_provider, agent_provider) {
(Some(default), Some(agent_specific)) if default.id != agent_specific.id => {
// Show both providers if they're different
info = info.add_key_value("Agent Provider (URL)", agent_specific.url.as_str());
if let Some(api_key) = agent_specific.api_key() {
info = info.add_key_value("Agent API Key", truncate_key(api_key.as_str()));
}
info = info.add_key_value("Default Provider (URL)", default.url.as_str());
if let Some(api_key) = default.api_key() {
info = info.add_key_value("Default API Key", truncate_key(api_key.as_str()));
}
}
(Some(provider), _) | (_, Some(provider)) => {
// Show single provider (either default or agent-specific)
info = info.add_key_value("Provider (URL)", provider.url.as_str());
if let Some(api_key) = provider.api_key() {
info = info.add_key_value("API Key", truncate_key(api_key.as_str()));
}
}
_ => {
// No provider available
}
}
// Add conversation information if available
if let Some(conversation) = conversation {
info = info.extend(Info::from(&conversation));
} else {
info = info.extend(Info::new().add_title("CONVERSATION").add_key("ID"));
}
if porcelain {
self.writeln(Porcelain::from(&info).into_long().skip(1))?;
} else {
self.writeln(info)?;
}
Ok(())
}
/// Generate ZSH plugin script
async fn on_zsh_plugin(&self) -> anyhow::Result<()> {
let plugin = crate::zsh::generate_zsh_plugin()?;
println!("{plugin}");
Ok(())
}
/// Generate ZSH theme
async fn on_zsh_theme(&self) -> anyhow::Result<()> {
let theme = crate::zsh::generate_zsh_theme()?;
println!("{theme}");
Ok(())
}
/// Run ZSH environment diagnostics
async fn on_zsh_doctor(&mut self) -> anyhow::Result<()> {
// Stop spinner before streaming output to avoid interference
self.spinner.stop(None)?;
// Stream the diagnostic output in real-time
crate::zsh::run_zsh_doctor()?;
Ok(())
}
/// Show ZSH keyboard shortcuts
async fn on_zsh_keyboard(&mut self) -> anyhow::Result<()> {
// Stop spinner before streaming output to avoid interference
self.spinner.stop(None)?;
// Stream the keyboard shortcuts output in real-time
crate::zsh::run_zsh_keyboard()?;
Ok(())
}
/// Install the Forge VS Code extension
async fn on_vscode_extension_install(&mut self) -> anyhow::Result<()> {
self.spinner
.start(Some("Installing Forge VS Code extension"))?;
match crate::vscode::install_extension() {
Ok(true) => {
self.spinner.stop(None)?;
self.writeln_title(TitleFormat::info(
"Forge VS Code extension installed successfully",
))?;
}
Ok(false) => {
self.spinner.stop(None)?;
self.writeln_title(TitleFormat::error(
"Failed to install Forge VS Code extension.",
))?;
}
Err(e) => {
self.spinner.stop(None)?;
self.writeln_title(TitleFormat::error(format!(
"Failed to install Forge VS Code extension: {e}"
)))?;
}
}
Ok(())
}
/// Setup ZSH integration by updating .zshrc
async fn on_zsh_setup(&mut self) -> anyhow::Result<()> {
// Check nerd font support
println!();
println!(
"{} {} {}",
"".bold(),
"FORGE 33.0k".bold(),
" tonic-1.0".cyan()
);
let can_see_nerd_fonts =
ForgeWidget::confirm("Can you see all the icons clearly without any overlap?")
.with_default(true)
.prompt()?;
let disable_nerd_font = match can_see_nerd_fonts {
Some(true) => {
println!();
false
}
Some(false) => {
println!();
println!(" {} Nerd Fonts will be disabled", "⚠".yellow());
println!();
println!(" You can enable them later by:");
println!(
" 1. Installing a Nerd Font from: {}",
"https://www.nerdfonts.com/".dimmed()
);
println!(" 2. Configuring your terminal to use a Nerd Font");
println!(
" 3. Removing {} from your ~/.zshrc",
"NERD_FONT=0".dimmed()
);
println!();
true
}
None => {
// User interrupted, default to not disabling
println!();
false
}
};
// Ask about editor preference
let editor_options = vec![
"Use system default ($EDITOR)",
"VS Code (code --wait)",
"Vim",
"Neovim (nvim)",
"Nano",
"Emacs",
"Sublime Text (subl --wait)",
"Skip - I'll configure it later",
];
let selected_editor = ForgeWidget::select(
"Which editor would you like to use for editing prompts?",
editor_options,
)
.prompt()?;
let forge_editor = match selected_editor {
Some("Use system default ($EDITOR)") => None,
Some("VS Code (code --wait)") => Some("code --wait"),
Some("Vim") => Some("vim"),
Some("Neovim (nvim)") => Some("nvim"),
Some("Nano") => Some("nano"),
Some("Emacs") => Some("emacs"),
Some("Sublime Text (subl --wait)") => Some("subl --wait"),
Some("Skip - I'll configure it later") => None,
_ => None,
};
// Setup ZSH integration with nerd font and editor configuration
self.spinner.start(Some("Configuring ZSH"))?;
let result = crate::zsh::setup_zsh_integration(disable_nerd_font, forge_editor)?;
self.spinner.stop(None)?;
// Log backup creation if one was made
if let Some(backup_path) = result.backup_path {
self.writeln_title(TitleFormat::debug(format!(
"backup created at {}",
backup_path.display()
)))?;
}
self.writeln_title(TitleFormat::info(result.message))?;
self.writeln_title(TitleFormat::debug("running forge zsh doctor"))?;
println!();
let doctor_result = self.on_zsh_doctor().await;
if doctor_result.is_ok() {
self.writeln_title(TitleFormat::action(
"run `exec zsh` now (or open a new terminal window) to load the updated shell config",
))?;
self.writeln_title(TitleFormat::action(
"run `: Hi` after restarting your shell to confirm everything works",
))?;
}
doctor_result
}
/// Handle the cmd command - generates shell command from natural language
async fn on_cmd(&mut self, prompt: UserPrompt) -> anyhow::Result<()> {
self.spinner.start(Some("Generating"))?;
match self.api.generate_command(prompt).await {
Ok(command) => {
self.spinner.stop(None)?;
self.writeln(command)?;
Ok(())
}
Err(err) => {
self.spinner.stop(None)?;
Err(err)
}
}
}
async fn list_conversations(&mut self) -> anyhow::Result<()> {
self.spinner.start(Some("Loading Conversations"))?;
let max_conversations = self.config.max_conversations;
let conversations = self.api.get_conversations(Some(max_conversations)).await?;
let conversations = Self::user_initiated_conversations(conversations);
self.spinner.stop(None)?;
if conversations.is_empty() {
self.writeln_title(TitleFormat::error(
"No conversations found in this workspace.",
))?;
return Ok(());
}
if let Some(conversation) = ConversationSelector::select_conversation(
&conversations,
self.state.conversation_id,
None,
)
.await?
{
let conversation_id = conversation.id;
self.state.conversation_id = Some(conversation_id);
// Show conversation content
self.on_show_last_message(conversation, false).await?;
// Print log about conversation switching
self.writeln_title(TitleFormat::info(format!(
"Switched to conversation {}",
conversation_id.into_string().bold()
)))?;
// Show conversation info
self.on_info(false, Some(conversation_id)).await?;
}
Ok(())
}
async fn on_show_conversations(&mut self, porcelain: bool) -> anyhow::Result<()> {
let max_conversations = self.config.max_conversations;
let conversations = self.api.get_conversations(Some(max_conversations)).await?;
let conversations = Self::user_initiated_conversations(conversations);
if conversations.is_empty() {
return Ok(());
}
let mut info = Info::new();
for conv in conversations.into_iter() {
if conv.context.is_none() {
continue;
}
let title = conv
.title
.as_deref()
.map(|t| t.to_string())
.unwrap_or_else(|| markers::EMPTY.to_string());
// Format time using humantime library (same as conversation_selector.rs)
let duration = chrono::Utc::now().signed_duration_since(
conv.metadata.updated_at.unwrap_or(conv.metadata.created_at),
);
let duration =
std::time::Duration::from_secs((duration.num_minutes() * 60).max(0) as u64);
let time_ago = if duration.is_zero() {
"now".to_string()
} else {
format!("{} ago", humantime::format_duration(duration))
};
// Add conversation: Title=<title>, Updated=<time_ago>, with ID as section title
info = info
.add_title(conv.id)
.add_key_value("Title", title)
.add_key_value("Updated", time_ago);
}
// In porcelain mode, skip the top-level "SESSIONS" title
if porcelain {
let porcelain = Porcelain::from(&info)
.drop_col(3)
.truncate(1, 60)
.uppercase_headers();
self.writeln(porcelain)?;
} else {
self.writeln(info)?;
}
Ok(())
}
fn user_initiated_conversations(conversations: Vec<Conversation>) -> Vec<Conversation> {
let related_ids: HashSet<ConversationId> = conversations
.iter()
.flat_map(Conversation::related_conversation_ids)
.collect();
conversations
.into_iter()
.filter(|conversation| {
conversation
.context
.as_ref()
.and_then(|context| context.initiator.as_deref())
.is_none_or(|initiator| initiator == "user")
&& !related_ids.contains(&conversation.id)
})
.collect()
}
async fn on_command(&mut self, command: AppCommand) -> anyhow::Result<bool> {
match command {
AppCommand::Conversations { id } => {
if let Some(raw_id) = id {
let conversation_id = ConversationId::parse(&raw_id)
.context(format!("Invalid conversation ID: {raw_id}"))?;
let conversation = self.validate_conversation_exists(&conversation_id).await?;
self.state.conversation_id = Some(conversation_id);
self.on_show_last_message(conversation, false).await?;
self.writeln_title(TitleFormat::info(format!(
"Switched to conversation {}",
conversation_id.into_string().bold()
)))?;
self.on_info(false, Some(conversation_id)).await?;
} else {
self.list_conversations().await?;
}
}
AppCommand::ConversationTree => {
let conversation_id = self
.state
.conversation_id
.ok_or_else(|| anyhow::anyhow!("No active conversation"))?;
let parent = self.validate_conversation_exists(&conversation_id).await?;
let children = self.fetch_related_conversations(&parent).await;
if children.is_empty() {
self.writeln_title(TitleFormat::info("No child conversations found."))?;
} else if let Some(conversation) = ConversationSelector::select_conversation(
&children,
self.state.conversation_id,
None,
)
.await?
{
let conversation_id = conversation.id;
self.state.conversation_id = Some(conversation_id);
self.on_show_last_message(conversation, false).await?;
self.writeln_title(TitleFormat::info(format!(
"Switched to conversation {}",
conversation_id.into_string().bold()
)))?;
self.on_info(false, Some(conversation_id)).await?;
}
}
AppCommand::Compact => {
self.spinner.start(Some("Compacting"))?;
self.on_compaction().await?;
}
AppCommand::Delete => {
self.handle_delete_conversation().await?;
}
AppCommand::Rename { ref name } => {
self.handle_rename_conversation(name.join(" ")).await?;
}
AppCommand::Dump { html, .. } => {
self.spinner.start(Some("Dumping"))?;
self.on_dump(html).await?;
}
AppCommand::New => {
self.on_new().await?;
}
AppCommand::Info => {
self.on_info(false, self.state.conversation_id).await?;
}
AppCommand::Usage => {
self.on_usage().await?;
}
AppCommand::Message(ref content) => {
self.spinner.start(None)?;
self.on_message(Some(content.clone())).await?;
}
AppCommand::Forge => {
self.on_agent_change(AgentId::FORGE).await?;
}
AppCommand::Muse => {
self.on_agent_change(AgentId::MUSE).await?;
}
AppCommand::Sage => {
self.on_agent_change(AgentId::SAGE).await?;
}
AppCommand::Help => {
let info = Info::from(self.command.as_ref());
self.writeln(info)?;
}
AppCommand::Tools => {
let agent_id = self.api.get_active_agent().await.unwrap_or_default();
self.on_show_tools(agent_id, false).await?;
}
AppCommand::Update => {
on_update(self.api.clone(), None).await;
}
AppCommand::Exit => {
return Ok(true);
}
AppCommand::Custom(event) => {
self.spinner.start(None)?;
self.on_custom_event(event.into()).await?;
}
AppCommand::Model => {
self.on_model_selection(None).await?;
}
AppCommand::Shell(ref command) => {
self.api.execute_shell_command_raw(command).await?;
}
AppCommand::Commit { max_diff_size, .. } => {
let args = CommitCommandGroup {
preview: false,
max_diff_size: max_diff_size.or(Some(100_000)),
diff: None,
text: Vec::new(),
};
let result = self.handle_commit_command(args).await?;
if !result.git_output.is_empty() {
self.writeln(result.git_output.trim_end())?;
} else {
self.writeln(result.message.trim_end())?;
}
}
AppCommand::Agent => {
if let Some(selected_agent) = self.select_agent(None).await? {
self.on_agent_change(selected_agent).await?;
}
}
AppCommand::Login => {
self.handle_provider_login(None).await?;
}
AppCommand::Logout => {
return self.handle_provider_logout(None).await;
}
AppCommand::Retry => {
self.spinner.start(None)?;
self.on_message(None).await?;
}
AppCommand::Index => {
let working_dir = self.state.cwd.clone();
self.on_index(working_dir, false).await?;
}
AppCommand::AgentSwitch(agent_id) => {
// Validate that the agent exists by checking against loaded agents
let agents = self.api.get_agent_infos().await?;
let agent_exists = agents.iter().any(|agent| agent.id.as_str() == agent_id);
if agent_exists {
self.on_agent_change(AgentId::new(agent_id)).await?;
} else {
return Err(anyhow::anyhow!(
"Agent '{agent_id}' not found or unavailable"
));
}
}
AppCommand::Config => {
self.on_show_config(false).await?;
}
AppCommand::ConfigModel => {
self.on_model_selection(None).await?;
}
AppCommand::ConfigReload => {
self.writeln_title(TitleFormat::info(
"No session overrides in REPL mode. Use :model to switch the active model.",
))?;
}
AppCommand::ReasoningEffort => {
self.on_reasoning_effort_selection(false).await?;
}
AppCommand::ConfigReasoningEffort => {
self.on_reasoning_effort_selection(true).await?;
}
AppCommand::ConfigCommitModel => {
self.on_config_commit_model().await?;
}
AppCommand::ConfigSuggestModel => {
self.on_config_suggest_model().await?;
}
AppCommand::ConfigEdit => {
self.on_config_edit().await?;
}
AppCommand::Skill => {
self.on_show_skills(false, false).await?;
}
AppCommand::Edit { content } => {
let initial = if content.is_empty() {
None
} else {
Some(content.join(" ").trim().to_string())
};
self.on_edit_buffer(initial).await?;
}
AppCommand::CommitPreview => {
let args = CommitCommandGroup {
preview: true,
max_diff_size: Some(100_000),
diff: None,
text: Vec::new(),
};
let result = self.handle_commit_command(args).await?;
let flags = if result.has_staged_files { "" } else { " -a" };
let commit_command = format!("!git commit{flags} -m '{}'", result.message);
self.console.set_buffer(commit_command);
}
AppCommand::Suggest { description } => {
let desc = if description.is_empty() {
None
} else {
Some(description.join(" ").trim().to_string())
};
self.on_suggest(desc).await?;
}
AppCommand::Clone { id } => {
self.on_slash_clone(id).await?;
}
AppCommand::ConversationRename { name } => {
let args = if name.is_empty() {
None
} else {
Some(name.join(" ").trim().to_string())
};
self.on_slash_conversation_rename(args).await?;
}
AppCommand::Copy => {
self.on_copy().await?;
}
AppCommand::WorkspaceSync => {
let working_dir = self.state.cwd.clone();
self.on_index(working_dir, true).await?;
}
AppCommand::WorkspaceStatus => {
let cwd = self.state.cwd.clone();
self.on_workspace_status(cwd, false).await?;
}
AppCommand::WorkspaceInfo => {
let cwd = self.state.cwd.clone();
self.on_workspace_info(cwd).await?;
}
AppCommand::WorkspaceInit => {
let cwd = self.state.cwd.clone();
self.on_workspace_init(cwd, false).await?;
}
}
Ok(false)
}
async fn on_compaction(&mut self) -> Result<(), anyhow::Error> {
let conversation_id = self.init_conversation().await?;
let compaction_result = self.api.compact_conversation(&conversation_id).await?;
let token_reduction = compaction_result.token_reduction_percentage();
let message_reduction = compaction_result.message_reduction_percentage();
let content = TitleFormat::action(format!(
"Context size reduced by {token_reduction:.1}% (tokens), {message_reduction:.1}% (messages)"
));
self.writeln_title(content)?;
Ok(())
}
async fn handle_delete_conversation(&mut self) -> anyhow::Result<()> {
let conversation_id = self.init_conversation().await?;
self.on_conversation_delete(conversation_id).await?;
Ok(())
}
async fn handle_rename_conversation(&mut self, name: String) -> anyhow::Result<()> {
let conversation_id = self.init_conversation().await?;
self.api
.rename_conversation(&conversation_id, name.clone())
.await?;
self.writeln_title(TitleFormat::info(format!(
"Conversation renamed to '{}'",
name.bold()
)))?;
Ok(())
}
/// Selects and sets the reasoning effort level interactively.
///
/// # Arguments
/// * `global` - If true, persists the change to the global config file. If
/// false, applies to the session (REPL has no separate session scope, so
/// this always writes to the config).
async fn on_reasoning_effort_selection(&mut self, global: bool) -> anyhow::Result<()> {
use std::str::FromStr;
let prompt = if global {
"Config Reasoning Effort"
} else {
"Reasoning Effort"
};
let selected = self.select_reasoning_effort(prompt, None).await?;
if let Some(effort_str) = selected {
let effort = forge_domain::Effort::from_str(&effort_str)
.map_err(|_| anyhow::anyhow!("Invalid effort level: {effort_str}"))?;
self.api
.update_config(vec![ConfigOperation::SetReasoningEffort(effort.clone())])
.await?;
self.writeln_title(
TitleFormat::action(effort_str).sub_title("is now the reasoning effort"),
)?;
}
Ok(())
}
async fn select_reasoning_effort(
&self,
prompt: &str,
query: Option<String>,
) -> anyhow::Result<Option<String>> {
let effort_levels = ["none", "minimal", "low", "medium", "high", "xhigh", "max"];
let current_effort = self.api.get_reasoning_effort().await.ok().flatten();
let current_str = current_effort.as_ref().map(|e| e.to_string());
let rows = effort_levels
.iter()
.map(|level| SelectRow::new(*level, *level))
.collect();
Ok(self
.select_raw_row(prompt, query, rows, 0, current_str)?
.map(|row| row.raw))
}
/// Selects and sets the commit model via interactive model picker.
async fn on_config_commit_model(&mut self) -> anyhow::Result<()> {
let selection = self.select_model(None, None).await?;
if let Some((model, provider_id)) = selection {
let commit_config = forge_domain::ModelConfig::new(provider_id.clone(), model.clone());
self.api
.update_config(vec![ConfigOperation::SetCommitConfig(Some(commit_config))])
.await?;
self.writeln_title(TitleFormat::action(model.as_str()).sub_title(format!(
"is now the commit model for provider '{provider_id}'"
)))?;
}
Ok(())
}
/// Selects and sets the suggest model via interactive model picker.
async fn on_config_suggest_model(&mut self) -> anyhow::Result<()> {
let selection = self.select_model(None, None).await?;
if let Some((model, provider_id)) = selection {
let suggest_config = forge_domain::ModelConfig::new(provider_id.clone(), model.clone());
self.api
.update_config(vec![ConfigOperation::SetSuggestConfig(suggest_config)])
.await?;
self.writeln_title(TitleFormat::action(model.as_str()).sub_title(format!(
"is now the suggest model for provider '{provider_id}'"
)))?;
}
Ok(())
}
/// Opens the global config file in the system editor.
async fn on_config_edit(&mut self) -> anyhow::Result<()> {
let config_path = forge_config::ConfigReader::config_path();
// Ensure parent directory exists
if let Some(parent) = config_path.parent() {
std::fs::create_dir_all(parent)?;
}
// Create config file if it does not exist
if !config_path.exists() {
std::fs::File::create(&config_path)?;
}
let editor = std::env::var("FORGE_EDITOR")
.or_else(|_| std::env::var("EDITOR"))
.unwrap_or_else(|_| "nano".to_string());
let editor_binary = editor
.split_whitespace()
.next()
.unwrap_or("nano")
.to_string();
let status = std::process::Command::new(&editor_binary)
.arg(&config_path)
.status()
.map_err(|e| {
anyhow::anyhow!(
"Failed to open editor '{}': {}. Set FORGE_EDITOR or EDITOR.",
editor_binary,
e
)
})?;
if !status.success() {
return Err(anyhow::anyhow!("Editor exited with error code: {}", status));
}
self.writeln_title(TitleFormat::info(format!(
"Config saved: {}",
config_path.display()
)))?;
Ok(())
}
/// Opens an external editor to compose a prompt and sets it in the REPL
/// buffer on exit.
///
/// # Arguments
/// * `initial` - Optional text to pre-populate the editor with.
async fn on_edit_buffer(&mut self, initial: Option<String>) -> anyhow::Result<()> {
use std::io::Write as _;
let editor = std::env::var("FORGE_EDITOR")
.or_else(|_| std::env::var("EDITOR"))
.unwrap_or_else(|_| "nano".to_string());
// Split the editor string into binary + pre-configured flags
// (e.g. "code --wait" → binary="code", extra_args=["--wait"])
let mut editor_parts = editor.split_whitespace();
let editor_binary = editor_parts.next().unwrap_or("nano").to_string();
let editor_flags: Vec<&str> = editor_parts.collect();
// Create .forge directory for the temp file
let forge_dir = self.state.cwd.join(".forge");
std::fs::create_dir_all(&forge_dir)?;
let temp_file = forge_dir.join("FORGE_EDITMSG.md");
// Write initial content
let mut file = std::fs::File::create(&temp_file)?;
if let Some(text) = initial {
file.write_all(text.as_bytes())?;
}
drop(file);
let status = std::process::Command::new(&editor_binary)
.args(&editor_flags)
.arg(&temp_file)
.status()
.map_err(|e| {
anyhow::anyhow!(
"Failed to open editor '{}': {}. Set FORGE_EDITOR or EDITOR.",
editor_binary,
e
)
})?;
if !status.success() {
return Err(anyhow::anyhow!("Editor exited with error code: {}", status));
}
let content = std::fs::read_to_string(&temp_file)?;
let content = content.trim().to_string();
if content.is_empty() {
self.writeln_title(TitleFormat::info("Editor closed with no content"))?;
return Ok(());
}
// Pre-fill the REPL buffer so the user can review/edit before sending
self.console.set_buffer(content);
Ok(())
}
/// Generates a shell command from a natural language description and sets
/// it in the REPL buffer.
///
/// # Arguments
/// * `description` - Optional natural language description. If `None`, an
/// interactive prompt is shown.
async fn on_suggest(&mut self, description: Option<String>) -> anyhow::Result<()> {
let description = match description {
Some(d) if !d.is_empty() => d,
_ => {
let input = ForgeWidget::input("Describe the command you want")
.allow_empty(false)
.prompt()?;
match input {
Some(d) if !d.is_empty() => d,
_ => {
self.writeln_title(TitleFormat::error(
"No description provided. Usage: :suggest <description>",
))?;
return Ok(());
}
}
}
};
self.spinner.start(Some("Generating"))?;
let prompt = UserPrompt::from(description);
match self.api.generate_command(prompt).await {
Ok(command) => {
self.spinner.stop(None)?;
self.writeln(command.clone())?;
// Set the generated command in the buffer for review
self.console.set_buffer(command);
Ok(())
}
Err(err) => {
self.spinner.stop(None)?;
Err(err)
}
}
}
/// Clones a conversation (current or selected) and switches to the clone.
///
/// # Arguments
/// * `id` - Optional conversation ID to clone. If `None`, the current
/// conversation is used; if no active conversation, an interactive picker
/// is shown.
async fn on_slash_clone(&mut self, id: Option<String>) -> anyhow::Result<()> {
let target_id = if let Some(id_str) = id {
ConversationId::parse(&id_str)
.map_err(|_| anyhow::anyhow!("Invalid conversation ID: {id_str}"))?
} else {
// Show conversation picker
let conversations = self
.api
.get_conversations(Some(self.config.max_conversations))
.await?;
if conversations.is_empty() {
self.writeln_title(TitleFormat::error(
"No conversations found. Start a conversation first.",
))?;
return Ok(());
}
let selected = ConversationSelector::select_conversation(
&conversations,
self.state.conversation_id,
None,
)
.await?;
match selected {
Some(conv) => conv.id,
None => return Ok(()),
}
};
// Fetch the conversation to clone
let original = self
.api
.conversation(&target_id)
.await?
.ok_or_else(|| anyhow::anyhow!("Conversation '{target_id}' not found"))?;
let original_id = original.id;
// Create the clone
let new_id = ConversationId::generate();
let mut cloned = original;
cloned.id = new_id;
self.api.upsert_conversation(cloned).await?;
// Switch to the cloned conversation
self.state.conversation_id = Some(new_id);
self.writeln_title(
TitleFormat::info("Cloned").sub_title(format!("[{original_id} → {new_id}]")),
)?;
Ok(())
}
/// Renames any conversation interactively or by explicit ID and name.
///
/// # Arguments
/// * `args` - Optional `"<id> <name>"` string. If `None`, shows a
/// conversation picker and prompts for a new name.
async fn on_slash_conversation_rename(&mut self, args: Option<String>) -> anyhow::Result<()> {
if let Some(args) = args {
// Parse as "<id> <name>"
let mut parts = args.splitn(2, ' ');
let id_str = parts.next().unwrap_or("").trim();
let name = parts.next().unwrap_or("").trim();
if id_str.is_empty() || name.is_empty() {
return Err(anyhow::anyhow!("Usage: :conversation-rename <id> <name>"));
}
let conversation_id = ConversationId::parse(id_str)
.map_err(|_| anyhow::anyhow!("Invalid conversation ID: {id_str}"))?;
self.api
.rename_conversation(&conversation_id, name.to_string())
.await?;
self.writeln_title(TitleFormat::info(format!(
"Conversation '{}' renamed to '{}'",
conversation_id.into_string().bold(),
name.bold()
)))?;
} else {
// Interactive: show picker then prompt for new name
let conversations = self
.api
.get_conversations(Some(self.config.max_conversations))
.await?;
if conversations.is_empty() {
self.writeln_title(TitleFormat::error("No conversations found."))?;
return Ok(());
}
let selected = ConversationSelector::select_conversation(
&conversations,
self.state.conversation_id,
None,
)
.await?;
if let Some(conv) = selected {
let name_result = ForgeWidget::input("New name").allow_empty(false).prompt()?;
if let Some(name) = name_result
&& !name.is_empty()
{
self.api.rename_conversation(&conv.id, name.clone()).await?;
self.writeln_title(TitleFormat::info(format!(
"Conversation renamed to '{}'",
name.bold()
)))?;
}
}
}
Ok(())
}
/// Copies the last AI response from the active conversation to the
/// system clipboard.
async fn on_copy(&mut self) -> anyhow::Result<()> {
let conversation_id = match &self.state.conversation_id {
Some(cid) => *cid,
None => {
self.writeln_title(TitleFormat::error(
"No active conversation. Start a conversation first.",
))?;
return Ok(());
}
};
let conversation = match self.api.conversation(&conversation_id).await? {
Some(conv) => conv,
None => {
self.writeln_title(TitleFormat::error("Conversation not found."))?;
return Ok(());
}
};
let context = match &conversation.context {
Some(ctx) => ctx.clone(),
None => {
self.writeln_title(TitleFormat::error("Conversation has no messages."))?;
return Ok(());
}
};
// Find the last assistant message
let content = context.messages.iter().rev().find_map(|msg| match &**msg {
forge_domain::ContextMessage::Text(forge_api::TextMessage {
content,
role: forge_domain::Role::Assistant,
..
}) => Some(content.clone()),
_ => None,
});
match content {
None => {
self.writeln_title(TitleFormat::error(
"No assistant message found in this conversation.",
))?;
}
Some(content) => {
#[cfg(not(target_os = "android"))]
let copied = arboard::Clipboard::new()
.and_then(|mut cb| cb.set_text(content.clone()))
.is_ok();
#[cfg(target_os = "android")]
let copied = false;
if copied {
let line_count = content.lines().count();
let byte_count = content.len();
self.writeln_title(TitleFormat::info(format!(
"Copied to clipboard [{line_count} lines, {byte_count} bytes]"
)))?;
} else {
self.writeln_title(TitleFormat::error(
"Failed to copy to clipboard. Ensure xclip/xsel (Linux) or pbcopy (macOS) is available.",
))?;
}
}
}
Ok(())
}
async fn select_agent(&self, query: Option<String>) -> Result<Option<AgentId>> {
let rows = self.agent_select_rows().await?;
let initial_raw = self
.api
.get_active_agent()
.await
.map(|current| current.as_str().to_string());
Ok(self
.select_raw_row("Agent", query, rows, 1, initial_raw)?
.map(|row| AgentId::new(row.raw)))
}
async fn agent_select_rows(&self) -> Result<Vec<SelectRow>> {
let info = self.build_agents_info(false).await?;
let porcelain = Porcelain::from(&info)
.drop_cols(&[0, 3])
.truncate(3, 30)
.uppercase_headers();
Self::porcelain_rows(porcelain)
}
/// Select a model from all configured providers using porcelain-style
/// tabular display matching the shell plugin's `:model` UI.
///
/// Shows columns: MODEL, PROVIDER, CONTEXT WINDOW, TOOL SUPPORTED, IMAGE
/// with a non-selectable header row.
///
/// When `provider_filter` is `Some`, only models belonging to that provider
/// are shown. This is used during onboarding so that after a provider is
/// selected the model list is scoped to that provider only.
///
/// # Returns
/// - `Ok(Some((ModelId, ProviderId)))` if a model was selected, carrying
/// both the model and the provider it belongs to
/// - `Ok(None)` if selection was canceled
#[async_recursion::async_recursion]
async fn select_model(
&mut self,
provider_filter: Option<ProviderId>,
query: Option<String>,
) -> Result<Option<(ModelId, ProviderId)>> {
// Check if provider is set otherwise first ask to select a provider
if provider_filter.is_none() && self.api.get_session_config().await.is_none() {
if !self.on_provider_selection().await? {
return Ok(None);
}
// Provider activation may have already completed model selection.
// If it did not, continue below and show the full cross-provider
// model list.
if self.api.get_session_config().await.is_some() {
return Ok(None);
}
}
// Fetch models from ALL configured providers (matches shell plugin's
// `forge list models --porcelain`), then optionally filter by provider.
self.spinner.start(Some("Loading"))?;
let mut all_provider_models = self.api.get_all_provider_models().await?;
self.spinner.stop(None)?;
// When a provider filter is specified (e.g. during onboarding after a
// provider was just selected), restrict the list to that provider's
// models so the user cannot accidentally pick a model from a different
// provider.
if let Some(ref filter_id) = provider_filter {
all_provider_models.retain(|pm| &pm.provider_id == filter_id);
}
if all_provider_models.is_empty() {
return Ok(None);
}
// Sort models and providers (same as on_show_models)
all_provider_models
.iter_mut()
.for_each(|pm| pm.models.sort_by(|a, b| a.id.as_str().cmp(b.id.as_str())));
all_provider_models.sort_by(|a, b| a.provider_id.as_ref().cmp(b.provider_id.as_ref()));
// Build the same Info structure as on_show_models, then convert to
// Porcelain for tabular display.
let mut info = Info::new();
for pm in &all_provider_models {
let provider_display = pm.provider_id.to_string();
for model in &pm.models {
let id = model.id.to_string();
info = info
.add_title(&id)
.add_key_value("Model", model.name.as_ref().unwrap_or(&id))
.add_key_value("Provider", &provider_display);
if let Some(limit) = model.context_length {
let context = if limit >= 1_000_000 {
format!("{}M", limit / 1_000_000)
} else if limit >= 1000 {
format!("{}k", limit / 1000)
} else {
format!("{limit}")
};
info = info.add_key_value("Context Window", context);
} else {
info = info.add_key_value("Context Window", markers::EMPTY);
}
if let Some(supported) = model.tools_supported {
info = info.add_key_value(
"Tool Supported",
if supported { status::YES } else { status::NO },
);
} else {
info = info.add_key_value("Tools", markers::EMPTY);
}
let supports_image = model
.input_modalities
.contains(&forge_domain::InputModality::Image);
info = info.add_key_value(
"Image",
if supports_image {
status::YES
} else {
status::NO
},
);
}
}
// Convert to porcelain format (same as on_show_models --porcelain)
let porcelain_output = Porcelain::from(&info)
.drop_col(0)
.truncate(0, 40)
.uppercase_headers();
let porcelain_str = porcelain_output.to_string();
// Split into header + data lines
let all_lines: Vec<&str> = porcelain_str.lines().collect();
if all_lines.is_empty() {
return Ok(None);
}
// Build a flat list of (ModelId, ProviderId) for the data rows.
// The first line is the header; data rows follow in the same order as
// the Info entries (sorted by provider, then model within provider).
let mut model_entries: Vec<(ModelId, ProviderId)> = Vec::new();
for pm in &all_provider_models {
for model in &pm.models {
model_entries.push((model.id.clone(), pm.provider_id.clone()));
}
}
let mut rows = Vec::with_capacity(all_lines.len());
// Header row (non-selectable via header_lines=1)
let Some(header) = all_lines.first() else {
return Err(UIError::MissingHeaderLine.into());
};
rows.push(SelectRow::header(header.to_string()));
// Data rows
for (i, line) in all_lines.iter().skip(1).enumerate() {
let Some((model_id, provider_id)) = model_entries.get(i) else {
continue;
};
let dotted_id = model_id.as_str().replace(['-', '_'], ".");
rows.push(SelectRow {
raw: format!("{}\t{}", model_id.as_str(), provider_id.as_ref()),
display: line.to_string(),
search: format!(
"{} {} {} {}",
model_id.as_str(),
dotted_id,
provider_id.as_ref(),
line
),
fields: vec![model_id.to_string(), provider_id.as_ref().to_string()],
});
}
// Find starting cursor position for the current model.
let current_model = self
.get_agent_model(self.api.get_active_agent().await)
.await;
let current_provider = self
.get_provider(self.api.get_active_agent().await)
.await
.ok()
.map(|provider| provider.id);
let initial_raw = current_model.as_ref().and_then(|current| {
model_entries
.iter()
.find(|(model_id, provider_id)| {
model_id == current
&& current_provider
.as_ref()
.map(|provider| provider_id == provider)
.unwrap_or(true)
})
.map(|(model_id, provider_id)| {
format!("{}\t{}", model_id.as_str(), provider_id.as_ref())
})
});
let selected = self.select_raw_row("Model ❯ ", query, rows, 1, initial_raw)?;
let Some(selected) = selected else {
return Ok(None);
};
let mut parts = selected.raw.splitn(2, '\t');
let selection = match (parts.next(), parts.next()) {
(Some(model_id), Some(provider_id)) => Some((
ModelId::new(model_id.to_string()),
ProviderId::from(provider_id.to_string()),
)),
_ => None,
};
Ok(selection)
}
async fn handle_api_key_input(
&mut self,
provider_id: ProviderId,
request: &ApiKeyRequest,
) -> anyhow::Result<()> {
use anyhow::Context;
self.spinner.stop(None)?;
// Extract existing API key and URL params for prefilling
let existing_url_params = request.existing_params.as_ref();
// Collect URL parameters if required
let url_params = request
.required_params
.iter()
.map(|param| {
let param_value = if let Some(options) = ¶m.options {
// Dropdown path: user selects from preset options
let starting = existing_url_params
.and_then(|p| p.get(¶m.name))
.and_then(|v| options.iter().position(|o| o.as_str() == v.as_str()))
.unwrap_or(0);
ForgeWidget::select(format!("Select {}", param.name), options.clone())
.with_starting_cursor(starting)
.prompt()?
.context("Parameter selection cancelled")?
} else {
// Free-text path
let label = if param.optional {
format!("Enter {} (optional, press Enter to skip)", param.name)
} else {
format!("Enter {}", param.name)
};
let mut input = ForgeWidget::input(label);
// Add default value if it exists in the credential
if let Some(params) = existing_url_params
&& let Some(default_value) = params.get(¶m.name)
{
input = input.with_default(default_value.as_str());
}
if param.optional {
input = input.allow_empty(true);
}
let param_value = input.prompt()?.context("Parameter input cancelled")?;
if !param.optional {
anyhow::ensure!(
!param_value.trim().is_empty(),
"{} cannot be empty",
param.name
);
}
param_value.trim_end_matches('/').to_string()
};
Ok((param.name.to_string(), param_value))
})
.collect::<anyhow::Result<HashMap<_, _>>>()?;
let allows_local_api_key = matches!(
provider_id.as_ref().as_ref(),
"ollama" | "vllm" | "lm_studio" | "llama_cpp" | "jan_ai"
);
// Check if API key is already provided
// For Google ADC, we use a marker to skip prompting
// For other providers, we use the existing key as a default value (autofill)
let api_key_str = if let Some(default_key) = &request.api_key {
let key_str = default_key.as_ref();
// Skip prompting for markers that indicate non-API-key auth
if key_str == "google_adc_marker" || key_str == "aws_profile_marker" {
key_str.to_string()
} else if allows_local_api_key {
let input = ForgeWidget::input(format!(
"Enter your {provider_id} API key (press Enter to skip)"
))
.allow_empty(true);
let api_key = input.prompt()?.context("API key input cancelled")?;
let api_key_str = api_key.trim();
if api_key_str.is_empty() {
"local".to_string()
} else {
api_key_str.to_string()
}
} else {
// For other providers, show the existing key as default (autofill)
let input = ForgeWidget::input(format!("Enter your {provider_id} API key"))
.with_default(key_str);
let api_key = input.prompt()?.context("API key input cancelled")?;
let api_key_str = api_key.trim();
anyhow::ensure!(!api_key_str.is_empty(), "API key cannot be empty");
api_key_str.to_string()
}
} else if allows_local_api_key {
let input = ForgeWidget::input(format!(
"Enter your {provider_id} API key (press Enter to skip)"
))
.allow_empty(true);
let api_key = input.prompt()?.context("API key input cancelled")?;
let api_key_str = api_key.trim();
if api_key_str.is_empty() {
"local".to_string()
} else {
api_key_str.to_string()
}
} else {
// Prompt for API key input (no existing key)
let input = ForgeWidget::input(format!("Enter your {provider_id} API key"));
let api_key = input.prompt()?.context("API key input cancelled")?;
let api_key_str = api_key.trim();
anyhow::ensure!(!api_key_str.is_empty(), "API key cannot be empty");
api_key_str.to_string()
};
// Update the context with collected data
let response = AuthContextResponse::api_key(request.clone(), &api_key_str, url_params);
self.api
.complete_provider_auth(
provider_id,
response,
Duration::from_secs(0), // No timeout needed since we have the data
)
.await?;
Ok(())
}
fn display_oauth_device_info_new(
&mut self,
user_code: &str,
verification_uri: &str,
verification_uri_complete: Option<&str>,
) -> anyhow::Result<()> {
use colored::Colorize;
let display_uri = verification_uri_complete.unwrap_or(verification_uri);
self.writeln("")?;
self.writeln(format!(
"{} Please visit: {}",
"→".blue(),
display_uri.blue().underline()
))?;
// Try to copy code to clipboard automatically (not available on Android)
#[cfg(not(target_os = "android"))]
let clipboard_copied = arboard::Clipboard::new()
.and_then(|mut clipboard| clipboard.set_text(user_code))
.is_ok();
#[cfg(target_os = "android")]
let clipboard_copied = false;
if clipboard_copied {
self.writeln(format!(
"{} Code copied to clipboard: {}",
"✓".green().bold(),
user_code.bold().yellow()
))?;
} else {
self.writeln(format!(
"{} Enter code: {}",
"→".blue(),
user_code.bold().yellow()
))?;
}
self.writeln("")?;
// Try to open browser automatically
if let Err(e) = open::that(display_uri) {
self.writeln_title(TitleFormat::error(format!(
"Failed to open browser automatically: {e}"
)))?;
}
Ok(())
}
async fn handle_device_flow(
&mut self,
provider_id: ProviderId,
request: &DeviceCodeRequest,
) -> Result<()> {
use std::time::Duration;
let user_code = request.user_code.clone();
let verification_uri = request.verification_uri.clone();
let verification_uri_complete = request.verification_uri_complete.clone();
self.spinner.stop(None)?;
// Display OAuth device information
self.display_oauth_device_info_new(
user_code.as_ref(),
verification_uri.as_ref(),
verification_uri_complete.as_ref().map(|v| v.as_ref()),
)?;
// Step 2: Complete authentication (polls if needed for OAuth flows)
self.spinner.start(Some("Completing authentication..."))?;
let response = AuthContextResponse::device_code(request.clone());
self.api
.complete_provider_auth(provider_id, response, Duration::from_secs(600))
.await?;
self.spinner.stop(None)?;
Ok(())
}
async fn display_credential_success(&mut self, provider_id: ProviderId) -> anyhow::Result<()> {
self.writeln_title(TitleFormat::info(format!(
"{provider_id} configured successfully"
)))?;
Ok(())
}
async fn handle_code_flow(
&mut self,
provider_id: ProviderId,
request: &CodeRequest,
) -> anyhow::Result<()> {
use colored::Colorize;
self.spinner.stop(None)?;
self.writeln(format!(
"{}",
format!("Authenticate using your {provider_id} account").dimmed()
))?;
let callback_server =
match crate::oauth_callback::LocalhostOAuthCallbackServer::start(request) {
Ok(Some(server)) => {
self.writeln(format!(
"{} Waiting for browser callback on {}",
"→".blue(),
server.redirect_uri().as_str().blue().underline()
))?;
Some(server)
}
Ok(None) | Err(_) => {
// Not a localhost callback flow, or the listener could not be
// started — fall back to manual code paste.
None
}
};
// Display authorization URL
self.writeln(format!(
"{} Please visit: {}",
"→".blue(),
request.authorization_url.as_str().blue().underline()
))?;
// Try to open browser automatically
if let Err(e) = open::that(request.authorization_url.as_str()) {
self.writeln_title(TitleFormat::error(format!(
"Failed to open browser automatically: {e}"
)))?;
}
let code = if let Some(server) = callback_server {
server.wait_for_code().await?
} else {
// Prompt user to paste authorization code
let code =
ForgeWidget::input(format!("Paste the authorization code for {provider_id}"))
.prompt()?
.ok_or_else(|| anyhow::anyhow!("Authorization code input cancelled"))?;
if code.trim().is_empty() {
anyhow::bail!("Authorization code cannot be empty");
}
code
};
self.spinner
.start(Some("Exchanging authorization code..."))?;
let response = AuthContextResponse::code(request.clone(), &code);
self.api
.complete_provider_auth(
provider_id,
response,
Duration::from_secs(0), // No timeout needed since we have the data
)
.await?;
self.spinner.stop(None)?;
Ok(())
}
/// Helper method to select an authentication method when multiple are
/// available
async fn select_auth_method(
&mut self,
provider_id: ProviderId,
auth_methods: &[AuthMethod],
) -> Result<Option<AuthMethod>> {
use colored::Colorize;
if auth_methods.is_empty() {
return Err(UIError::NoAuthMethodsAvailable { provider: provider_id.clone() }.into());
}
// If only one auth method, use it directly
if auth_methods.len() == 1 {
let Some(method) = auth_methods.first() else {
return Err(
UIError::NoAuthMethodsAvailable { provider: provider_id.clone() }.into(),
);
};
return Ok(Some(method.clone()));
}
// Multiple auth methods - ask user to choose
self.spinner.stop(None)?;
self.writeln_title(TitleFormat::action(format!("Configure {provider_id}")))?;
self.writeln("Multiple authentication methods available".dimmed())?;
let method_names: Vec<String> = auth_methods
.iter()
.map(|method| match method {
AuthMethod::ApiKey => "API Key".to_string(),
AuthMethod::OAuthDevice(_) => "OAuth Device Flow".to_string(),
AuthMethod::OAuthCode(_) => "OAuth Authorization Code".to_string(),
AuthMethod::GoogleAdc => "Google Application Default Credentials (ADC)".to_string(),
AuthMethod::AwsProfile => "AWS Profile (SSO/IAM)".to_string(),
AuthMethod::CodexDevice(_) => "OpenAI Codex Device Flow".to_string(),
})
.collect();
match ForgeWidget::select("Select authentication method:", method_names.clone())
.with_help_message("Use arrow keys to navigate and Enter to select")
.prompt()?
{
Some(selected_name) => {
// Find the corresponding auth method
let Some(index) = method_names.iter().position(|name| name == &selected_name)
else {
return Err(UIError::AuthMethodNotFound.into());
};
let Some(method) = auth_methods.get(index) else {
return Err(UIError::AuthMethodNotFound.into());
};
Ok(Some(method.clone()))
}
None => Ok(None),
}
}
/// Creates ForgeCode Services credentials if not already authenticated and
/// displays the credentials file location to the user.
async fn init_forge_services(&mut self) -> Result<()> {
self.api.create_auth_credentials().await?;
let env = self.api.environment();
let credentials_path = crate::info::format_path_for_display(&env, &env.credentials_path());
self.writeln_title(
TitleFormat::info("ForgeCode Services enabled").sub_title(&credentials_path),
)?;
Ok(())
}
/// Handle authentication flow for an unavailable provider
async fn configure_provider(
&mut self,
provider_id: ProviderId,
auth_methods: Vec<AuthMethod>,
) -> Result<Option<Provider<Url>>> {
if provider_id == ProviderId::FORGE_SERVICES {
self.init_forge_services().await?;
return Ok(None);
}
// Select auth method (or use the only one available)
let auth_method = match self
.select_auth_method(provider_id.clone(), &auth_methods)
.await?
{
Some(method) => method,
None => return Ok(None), // User cancelled
};
// Show warning for Claude Code provider about account ban risk
if provider_id == ProviderId::CLAUDE_CODE {
self.writeln_title(
TitleFormat::warning(
"Using Claude Code subscription in third-party tools violates Anthropic's Terms of Service."
)
.sub_title("Your account may be suspended or banned. Continue at your own risk."),
)?;
let confirmed = ForgeWidget::confirm("Do you want to continue with this provider?")
.with_default(false)
.prompt()?;
if !confirmed.unwrap_or(false) {
return Ok(None);
}
}
self.spinner.start(Some("Initiating authentication..."))?;
// Initiate the authentication flow
let auth_request = self
.api
.init_provider_auth(provider_id.clone(), auth_method)
.await?;
// Handle the specific authentication flow based on the request type
match auth_request {
AuthContextRequest::ApiKey(request) => {
self.handle_api_key_input(provider_id.clone(), &request)
.await?;
}
AuthContextRequest::DeviceCode(request) => {
self.handle_device_flow(provider_id.clone(), &request)
.await?;
}
AuthContextRequest::Code(request) => {
self.handle_code_flow(provider_id.clone(), &request).await?;
}
}
// Verify by fetching the configured provider
let provider = self.api.get_provider(&provider_id).await?;
self.display_credential_success(provider_id.clone()).await?;
Ok(provider.into_configured())
}
/// Builds a porcelain-style provider selection list from a set of
/// providers, displays it in the interactive picker, and returns the
/// selected provider.
///
/// The display matches the shell plugin's `_forge_select_provider`:
/// columns NAME, HOST, TYPE, LOGGED IN (hiding the raw ID column).
fn select_provider_from_list(
&self,
providers: Vec<AnyProvider>,
prompt: &str,
current_provider_id: Option<ProviderId>,
query: Option<String>,
) -> Result<Option<AnyProvider>> {
if providers.is_empty() {
return Ok(None);
}
// Sort providers alphabetically by display name
let mut sorted = providers;
sorted.sort_by_key(|a| a.id().to_string());
// Build Info structure (same as on_show_providers)
let mut info = Info::new();
for provider in &sorted {
let id: &str = &provider.id();
let display_name = provider.id().to_string();
let domain = if let Some(url) = provider.url() {
url.domain().map(|d| d.to_string()).unwrap_or_default()
} else {
markers::EMPTY.to_string()
};
let provider_type = provider.provider_type().to_string();
let configured = provider.is_configured();
info = info
.add_title(id.to_case(Case::UpperSnake))
.add_key_value("name", display_name)
.add_key_value("id", id)
.add_key_value("host", domain)
.add_key_value("type", provider_type);
if configured {
info = info.add_key_value("logged in", status::YES);
}
}
// Convert to porcelain, drop title (col 0) and raw id (col 2)
let porcelain_output = Porcelain::from(&info)
.drop_cols(&[0, 2])
.uppercase_headers();
let porcelain_str = porcelain_output.to_string();
let all_lines: Vec<&str> = porcelain_str.lines().collect();
if all_lines.is_empty() {
return Ok(None);
}
let Some(header) = all_lines.first() else {
return Err(UIError::MissingHeaderLine.into());
};
let mut rows = vec![SelectRow::header(header.to_string())];
for (index, line) in all_lines.iter().skip(1).enumerate() {
if let Some(provider) = sorted.get(index) {
rows.push(SelectRow::new(
provider.id().as_ref().to_string(),
line.to_string(),
));
}
}
let selected = self.select_raw_row(
prompt,
query,
rows,
1,
current_provider_id.map(|current| current.as_ref().to_string()),
)?;
Ok(selected.and_then(|row| {
sorted
.into_iter()
.find(|provider| provider.id().as_ref().as_ref() == row.raw)
}))
}
/// Selects a provider, optionally configuring it if not already configured.
async fn select_provider(
&mut self,
query: Option<String>,
configured_only: bool,
) -> Result<Option<AnyProvider>> {
let mut providers: Vec<AnyProvider> = self
.api
.get_providers()
.await?
.into_iter()
.filter(|p| {
let filter = forge_domain::ProviderType::Llm;
match &p {
AnyProvider::Url(provider) => provider.provider_type == filter,
AnyProvider::Template(provider) => provider.provider_type == filter,
}
})
.collect();
if configured_only {
providers.retain(|provider| provider.is_configured());
}
if providers.is_empty() {
return Err(anyhow::anyhow!("No AI provider API keys configured"));
}
let current_provider_id = self
.get_provider(self.api.get_active_agent().await)
.await
.ok()
.map(|p| p.id);
self.select_provider_from_list(providers, "Provider", current_provider_id, query)
}
// Helper method to handle model selection and update the conversation.
// When `provider_filter` is `Some`, only models from that provider are shown.
// The model and provider returned by the selector are always set as one
// atomic operation.
#[async_recursion::async_recursion]
async fn on_model_selection(
&mut self,
provider_filter: Option<ProviderId>,
) -> Result<Option<ModelId>> {
// Select a model; the selector returns both the model and its provider
let selection = self.select_model(provider_filter, None).await?;
// If no model was selected (user canceled), return early
let (model, provider_id) = match selection {
Some(pair) => pair,
None => return Ok(None),
};
// Set model and provider atomically as a single config operation
self.api
.update_config(vec![ConfigOperation::SetSessionConfig(
forge_domain::ModelConfig::new(provider_id, model.clone()),
)])
.await?;
// Update the UI state with the new model
self.update_model(Some(model.clone()));
self.writeln_title(TitleFormat::action(format!("Switched to model: {model}")))?;
Ok(Some(model))
}
async fn on_provider_selection(&mut self) -> Result<bool> {
// Select a provider
// If no provider was selected (user canceled), return early
let any_provider = match self.select_provider(None, false).await? {
Some(provider) => provider,
None => return Ok(false),
};
self.activate_provider(any_provider).await?;
// Check if provider was actually saved — if user cancelled model selection
// inside activate_provider, nothing was written
Ok(self.api.get_session_config().await.is_some())
}
/// Activates a provider by configuring it if needed, setting it as default,
/// and ensuring a compatible model is selected.
async fn activate_provider(&mut self, any_provider: AnyProvider) -> Result<()> {
self.activate_provider_with_model(any_provider, None).await
}
/// Activates a provider with an optional pre-selected model.
/// When `model` is provided, the interactive model selection prompt is
/// skipped and the specified model is set directly.
async fn activate_provider_with_model(
&mut self,
any_provider: AnyProvider,
model: Option<ModelId>,
) -> Result<()> {
// Trigger authentication for the selected provider only if not configured
let provider = if !any_provider.is_configured() {
match self
.configure_provider(any_provider.id(), any_provider.auth_methods().to_vec())
.await?
{
Some(provider) => provider,
None => return Ok(()),
}
} else {
// Provider is already configured, convert it
match any_provider.into_configured() {
Some(provider) => provider,
None => return Ok(()),
}
};
// Set as default and handle model selection
self.finalize_provider_activation(provider, model).await
}
/// Finalizes provider activation by setting it as default and ensuring
/// a compatible model is selected.
/// When `model` is `Some`, the interactive model selection is skipped and
/// the provided model is validated and set directly.
async fn finalize_provider_activation(
&mut self,
provider: Provider<Url>,
model: Option<ModelId>,
) -> Result<()> {
// If a model was pre-selected (e.g. from :model), validate and set it
// directly without prompting
if let Some(model) = model {
let model_id = self
.validate_model(model.as_str(), Some(&provider.id))
.await?;
self.api
.update_config(vec![ConfigOperation::SetSessionConfig(
forge_domain::ModelConfig::new(provider.id.clone(), model_id.clone()),
)])
.await?;
self.writeln_title(
TitleFormat::action(format!("{}", provider.id))
.sub_title("is now the default provider"),
)?;
self.writeln_title(
TitleFormat::action(model_id.as_str()).sub_title("is now the default model"),
)?;
return Ok(());
}
// Check if the current model is available for the new provider
let current_model = self.api.get_session_config().await.map(|c| c.model);
let (needs_model_selection, compatible_model) = match current_model {
None => (true, None),
Some(current_model) => {
let provider_models = self.api.get_all_provider_models().await?;
let model_available = provider_models
.iter()
.find(|pm| pm.provider_id == provider.id)
.map(|pm| pm.models.iter().any(|m| m.id == current_model))
.unwrap_or(false);
if model_available {
(false, Some(current_model))
} else {
(true, None)
}
}
};
if needs_model_selection {
let selected = self.on_model_selection(Some(provider.id.clone())).await?;
if selected.is_none() {
// User cancelled — preserve existing config untouched
return Ok(());
}
} else {
// The current model is compatible with the new provider — write both
// atomically so the session always stores a consistent pair.
let model =
compatible_model.expect("compatible_model is Some when !needs_model_selection");
self.api
.update_config(vec![ConfigOperation::SetSessionConfig(
forge_domain::ModelConfig::new(provider.id.clone(), model),
)])
.await?;
self.writeln_title(
TitleFormat::action(format!("{}", provider.id))
.sub_title("is now the default provider"),
)?;
}
Ok(())
}
// Handle dispatching events from the CLI
async fn handle_dispatch(&mut self, json: String) -> Result<()> {
// Initialize the conversation
let conversation_id = self.init_conversation().await?;
// Parse the JSON to determine the event name and value
let event: UserCommand = serde_json::from_str(&json)?;
// Create the chat request with the event
let chat = ChatRequest::new(event.into(), conversation_id);
self.on_chat(chat).await
}
/// Initializes and returns a conversation ID for the current session.
///
/// Handles conversation setup for both interactive and headless modes:
/// - **Interactive**: Reuses existing conversation, loads from file, or
/// creates new
/// - **Headless**: Uses environment variables or generates new conversation
///
/// Displays initialization status and updates UI state with the
/// conversation ID.
async fn init_conversation(&mut self) -> Result<ConversationId> {
// Set agent if provided via CLI
if let Some(agent_id) = self.cli.agent.clone() {
self.api.set_active_agent(agent_id).await?;
}
let mut is_new = false;
let id = if let Some(id) = self.state.conversation_id {
id
} else if let Some(id) = self.cli.conversation_id {
// Use the provided conversation ID
// Check if conversation exists, if not create it
if self.api.conversation(&id).await?.is_none() {
let conversation = Conversation::new(id);
self.api.upsert_conversation(conversation).await?;
is_new = true;
}
id
} else if let Some(ref path) = self.cli.conversation {
let content = ForgeFS::read_utf8(path).await?;
// Try to parse as a dump file first (with "conversation" wrapper)
let conversation: Conversation = if let Ok(dump) =
serde_json::from_str::<ConversationDump>(&content)
{
dump.conversation
} else {
// Fall back to parsing as direct Conversation object
serde_json::from_str(&content)
.context("Failed to parse conversation file. Expected either a ConversationDump or Conversation format")?
};
let id = conversation.id;
self.api.upsert_conversation(conversation).await?;
id
} else {
let conversation = Conversation::generate();
let id = conversation.id;
is_new = true;
self.api.upsert_conversation(conversation).await?;
id
};
// Print if the state is being reinitialized
if self.state.conversation_id.is_none() {
self.print_conversation_status(is_new, id)?;
}
// Always set the conversation id in state
self.state.conversation_id = Some(id);
Ok(id)
}
fn print_conversation_status(
&mut self,
new_conversation: bool,
id: ConversationId,
) -> Result<(), anyhow::Error> {
let mut title = if new_conversation {
"Initialize".to_string()
} else {
"Continue".to_string()
};
title.push_str(format!(" {}", id.into_string()).as_str());
self.writeln_title(TitleFormat::debug(title))?;
Ok(())
}
/// Initialize the state of the UI
async fn init_state(&mut self, first: bool) -> Result<()> {
let _ = self.handle_migrate_credentials().await;
// Ensure we have a model selected before proceeding with initialization
let active_agent = self.api.get_active_agent().await;
// Validate provider is configured before loading agents
// If provider is set in config but not configured (no credentials), prompt user
// to login
if self.api.get_session_config().await.is_none() && !self.on_provider_selection().await? {
return Ok(());
}
let mut operating_model = self.get_agent_model(active_agent.clone()).await;
if operating_model.is_none() {
// Use the model returned from selection instead of re-fetching
operating_model = self.on_model_selection(None).await?;
}
if first {
// For chat, we are trying to get active agent or setting it to default.
// So for default values, `/info` doesn't show active provider, model, etc.
// So my default, on new, we should set the active agent.
self.api
.set_active_agent(active_agent.clone().unwrap_or_default())
.await?;
// only call on_update if this is the first initialization
on_update(self.api.clone(), self.config.updates.as_ref()).await;
// Apply the MCP trust gate. Servers are NOT connected here —
// connections remain lazy and happen on first tool use.
self.api.init_mcp().await?;
}
// Execute independent operations in parallel to improve performance
let (agents_result, commands_result) =
tokio::join!(self.api.get_agent_infos(), self.api.get_commands());
// Register agent commands with proper error handling and user feedback
match agents_result {
Ok(agents) => {
let registration_result = self.command.register_agent_commands(agents);
// Show warning for any skipped agents due to conflicts
for skipped_command in registration_result.skipped_conflicts {
self.writeln_title(TitleFormat::error(format!(
"Skipped agent command '{skipped_command}' due to name conflict with built-in command"
)))?;
}
}
Err(e) => {
self.writeln_title(TitleFormat::error(format!(
"Failed to load agents for command registration: {e}"
)))?;
}
}
// Register all the commands
self.command.register_all(commands_result?);
self.state = UIState::new(self.api.environment());
self.update_model(operating_model);
Ok(())
}
async fn on_message(&mut self, content: Option<String>) -> Result<()> {
let conversation_id = self.init_conversation().await?;
if self.config.auto_install_vscode_extension {
self.install_vscode_extension();
}
// Track if content was provided to decide whether to use piped input as
// additional context
let has_content = content.is_some();
// Create a ChatRequest with the appropriate event type
let mut event = match content {
Some(text) => Event::new(text),
None => Event::empty(),
};
// Only use CLI piped_input as additional context when BOTH --prompt and piped
// input are provided. This handles the case: `echo "context" | forge -p
// "question"` where piped input provides context and --prompt provides
// the actual question.
//
// When only piped input is provided (no --prompt), it's already used as the
// main content (passed via the `content` parameter). We must NOT add it again
// as additional_context, otherwise the input appears twice in the
// conversation. We detect this by checking if cli.prompt exists - if it
// does, the content came from --prompt and piped input should be
// additional context.
let piped_input = self.cli.piped_input.clone();
let has_explicit_prompt = self.cli.prompt.is_some();
if let Some(piped) = piped_input
&& has_content
&& has_explicit_prompt
{
event = event.additional_context(piped);
}
// Create the chat request with the event
let chat = ChatRequest::new(event, conversation_id);
self.on_chat(chat).await
}
async fn on_chat(&mut self, chat: ChatRequest) -> Result<()> {
let mut stream = self.api.chat(chat).await?;
// Always use streaming content writer
let mut writer = StreamingWriter::new(self.spinner.clone(), self.api.clone());
while let Some(message) = stream.next().await {
match message {
Ok(message) => self.handle_chat_response(message, &mut writer).await?,
Err(err) => {
writer.finish()?;
self.spinner.stop(None)?;
self.spinner.reset();
return Err(err);
}
}
}
writer.finish()?;
self.spinner.stop(None)?;
self.spinner.reset();
Ok(())
}
/// Fetches related conversations for a given conversation in parallel.
///
/// Returns a vector of related conversations that could be successfully
/// fetched.
async fn fetch_related_conversations(&self, conversation: &Conversation) -> Vec<Conversation> {
let related_ids = conversation.related_conversation_ids();
// Fetch all related conversations in parallel
let related_futures: Vec<_> = related_ids
.iter()
.map(|id| {
let api = self.api.clone();
let id = *id;
async move { api.conversation(&id).await }
})
.collect();
future::join_all(related_futures)
.await
.into_iter()
.filter_map(|result| result.ok().flatten())
.collect()
}
/// Modified version of handle_dump that supports HTML format
async fn on_dump(&mut self, html: bool) -> Result<()> {
if let Some(conversation_id) = self.state.conversation_id {
let conversation = self.api.conversation(&conversation_id).await?;
if let Some(conversation) = conversation {
let timestamp = chrono::Local::now().format("%Y-%m-%d_%H-%M-%S");
// Collect related conversations from agent tool calls
let related_conversations = self.fetch_related_conversations(&conversation).await;
if html {
// Create a single HTML with all conversations
let html_content = if related_conversations.is_empty() {
// No related conversations, just render the main one
conversation.to_html()
} else {
// Render main conversation with related conversations in the same HTML
conversation.to_html_with_related(&related_conversations)
};
let path = format!("{timestamp}-dump.html");
tokio::fs::write(path.as_str(), &html_content).await?;
let subtitle = if related_conversations.is_empty() {
path.to_string()
} else {
format!("{} (+ {} related)", path, related_conversations.len())
};
self.writeln_title(
TitleFormat::action("Conversation HTML dump created".to_string())
.sub_title(subtitle),
)?;
if self.config.auto_open_dump {
open::that(path.as_str()).ok();
}
} else {
let dump_data = ConversationDump {
conversation: conversation.clone(),
related_conversations: related_conversations.clone(),
};
let path = format!("{timestamp}-dump.json");
let content = serde_json::to_string_pretty(&dump_data)?;
tokio::fs::write(path.as_str(), content).await?;
let subtitle = if related_conversations.is_empty() {
path.to_string()
} else {
format!("{} (+ {} related)", path, related_conversations.len())
};
self.writeln_title(
TitleFormat::action("Conversation JSON dump created".to_string())
.sub_title(subtitle),
)?;
if self.config.auto_open_dump {
open::that(path.as_str()).ok();
}
};
} else {
return Err(anyhow::anyhow!("Could not create dump"))
.context(format!("Conversation: {conversation_id} was not found"));
}
} else {
return Err(anyhow::anyhow!("No conversation initiated yet"))
.context("Could not create dump");
}
Ok(())
}
async fn handle_chat_response(
&mut self,
message: ChatResponse,
writer: &mut StreamingWriter<A>,
) -> Result<()> {
if message.is_empty() {
return Ok(());
}
match message {
ChatResponse::TaskMessage { content } => match content {
ChatResponseContent::ToolInput(title) => {
writer.finish()?;
self.writeln(title.display())?;
}
ChatResponseContent::ToolOutput(text) => {
writer.finish()?;
self.writeln(text)?;
}
ChatResponseContent::Markdown { text, partial: _ } => {
writer.write(&text)?;
}
},
ChatResponse::ToolCallStart { tool_call, notifier } => {
// Scope guard to ensure notification happens even on error.
// If writer.finish() or spinner.stop() fails, the guard's drop
// will still notify orch, preventing the deadlock.
struct NotifyGuard<'a>(&'a tokio::sync::Notify);
impl<'a> Drop for NotifyGuard<'a> {
fn drop(&mut self) {
self.0.notify_one();
}
}
let _guard = NotifyGuard(¬ifier);
writer.finish()?;
// Stop spinner only for tools that require stdout/stderr access
if tool_call.requires_stdout() {
self.spinner.stop(None)?;
}
// Notify orch that the UI has rendered the tool header.
// Orch awaits this before executing the tool, preventing tool
// stdout from appearing before the tool name is printed.
drop(_guard);
}
ChatResponse::ToolCallEnd(toolcall_result) => {
// Only track toolcall name in case of success else track the error.
let payload = if toolcall_result.is_error() {
let mut r = ToolCallPayload::new(toolcall_result.name.to_string());
if let Some(cause) = toolcall_result.output.as_str() {
r = r.with_cause(cause.to_string());
}
r
} else {
ToolCallPayload::new(toolcall_result.name.to_string())
};
tracker::tool_call(payload);
self.spinner.start(None)?;
if !self.cli.verbose {
return Ok(());
}
}
ChatResponse::RetryAttempt { cause, duration: _ } => {
if !self
.config
.retry
.as_ref()
.is_some_and(|r| r.suppress_errors)
{
writer.finish()?;
self.spinner.start(Some("Retrying"))?;
self.writeln_title(TitleFormat::error(cause.as_str()))?;
}
}
ChatResponse::Interrupt { reason } => {
writer.finish()?;
self.spinner.stop(None)?;
let title = match reason {
InterruptionReason::MaxRequestPerTurnLimitReached { limit } => {
format!("Maximum request ({limit}) per turn achieved")
}
InterruptionReason::MaxToolFailurePerTurnLimitReached { limit, .. } => {
format!("Maximum tool failure limit ({limit}) reached for this turn")
}
};
self.writeln_title(TitleFormat::action(title))?;
let continued = self.should_continue().await?;
if !continued && let Some(conversation_id) = self.state.conversation_id {
self.writeln_title(
TitleFormat::debug("Finished").sub_title(conversation_id.into_string()),
)?;
}
}
ChatResponse::TaskReasoning { content } => {
writer.write_dimmed(&content)?;
}
ChatResponse::TaskComplete => {
writer.finish()?;
if let Some(conversation_id) = self.state.conversation_id {
self.writeln_title(
TitleFormat::debug("Finished").sub_title(conversation_id.into_string()),
)?;
}
if let Some(format) = self.config.auto_dump.clone() {
let html = matches!(format, forge_config::AutoDumpFormat::Html);
self.on_dump(html).await?;
}
}
}
Ok(())
}
async fn should_continue(&mut self) -> anyhow::Result<bool> {
let should_continue = ForgeWidget::confirm("Do you want to continue anyway?")
.with_default(true)
.prompt()?;
if should_continue.unwrap_or(false) {
self.spinner.start(None)?;
Box::pin(self.on_message(None)).await?;
Ok(true)
} else {
Ok(false)
}
}
async fn on_show_conv_info(&mut self, conversation: Conversation) -> anyhow::Result<()> {
self.spinner.start(Some("Loading Summary"))?;
let info = Info::default().extend(&conversation);
self.writeln(info)?;
self.spinner.stop(None)?;
Ok(())
}
async fn on_show_conv_stats(
&mut self,
conversation: Conversation,
porcelain: bool,
) -> anyhow::Result<()> {
let mut info = Info::new().add_title("CONVERSATION");
// Add conversation ID
info = info.add_key_value("ID", conversation.id.to_string());
// Calculate duration
let created_at = conversation.metadata.created_at;
let updated_at = conversation.metadata.updated_at.unwrap_or(created_at);
let duration = updated_at.signed_duration_since(created_at);
// Format duration
let duration_str = if duration.num_hours() > 0 {
format!("{}h {}m", duration.num_hours(), duration.num_minutes() % 60)
} else if duration.num_minutes() > 0 {
format!(
"{}m {}s",
duration.num_minutes(),
duration.num_seconds() % 60
)
} else {
format!("{}s", duration.num_seconds())
};
info = info.add_key_value("Total Duration", duration_str);
// Add message statistics if context exists
if let Some(context) = &conversation.context {
info = info
.add_key_value("Total Messages", context.total_messages().to_string())
.add_key_value("User Messages", context.user_message_count().to_string())
.add_key_value(
"Assistant Messages",
context.assistant_message_count().to_string(),
)
.add_key_value("Tool Calls", context.tool_call_count().to_string());
}
// Add token usage if available
if let Some(usage) = conversation.usage().as_ref() {
info = info
.add_title("TOKEN")
.add_key_value("Prompt Tokens", usage.prompt_tokens.to_string())
.add_key_value("Completion Tokens", usage.completion_tokens.to_string())
.add_key_value("Total Tokens", usage.total_tokens.to_string());
}
if let Some(cost) = conversation.accumulated_cost() {
info = info.add_key_value("Cost", format!("${cost:.4}"));
}
if porcelain {
use convert_case::Case;
self.writeln(
Porcelain::from(&info)
.into_long()
.skip(1)
.to_case(&[0, 1], Case::Snake)
.sort_by(&[0, 1]),
)?;
} else {
self.writeln(info)?;
}
Ok(())
}
/// Clones a conversation with a new ID
///
/// # Arguments
/// * `original` - The conversation to clone
/// * `porcelain` - If true, output only the new conversation ID
async fn on_clone_conversation(
&mut self,
original: Conversation,
porcelain: bool,
) -> anyhow::Result<()> {
// Create a new conversation with a new ID but same content
let new_id = ConversationId::generate();
let mut cloned = original.clone();
cloned.id = new_id;
// Upsert the cloned conversation
self.api.upsert_conversation(cloned.clone()).await?;
// Output based on format
if porcelain {
println!("{new_id}");
} else {
self.writeln_title(
TitleFormat::info("Cloned").sub_title(format!("[{} → {}]", original.id, cloned.id)),
)?;
}
Ok(())
}
fn update_model(&mut self, model: Option<ModelId>) {
if let Some(ref model) = model {
tracker::set_model(model.to_string());
}
}
async fn on_custom_event(&mut self, event: Event) -> Result<()> {
let conversation_id = self.init_conversation().await?;
let chat = ChatRequest::new(event, conversation_id);
self.on_chat(chat).await
}
async fn on_usage(&mut self) -> anyhow::Result<()> {
self.spinner.start(Some("Loading Usage"))?;
// Get usage from current conversation if available
let conversation_usage = if let Some(conversation_id) = &self.state.conversation_id {
self.api
.conversation(conversation_id)
.await
.ok()
.flatten()
.and_then(|conv| conv.accumulated_usage())
} else {
None
};
let mut info = if let Some(usage) = conversation_usage {
Info::from(&usage)
} else {
Info::new()
};
if let Ok(Some(user_usage)) = self.api.user_usage().await {
info = info.extend(Info::from(&user_usage));
}
self.writeln(info)?;
self.spinner.stop(None)?;
Ok(())
}
fn trace_user(&self) {
let api = self.api.clone();
// NOTE: Spawning required so that we don't block the user while querying user
// info
tokio::spawn(async move {
if let Ok(Some(user_info)) = api.user_info().await {
tracker::login(user_info.auth_provider_id.into_string());
}
});
}
/// Handle config command
async fn handle_config_command(
&mut self,
command: crate::cli::ConfigCommand,
porcelain: bool,
) -> Result<()> {
match command {
crate::cli::ConfigCommand::Set(args) => self.handle_config_set(args).await?,
crate::cli::ConfigCommand::Get(args) => self.handle_config_get(args).await?,
crate::cli::ConfigCommand::List => {
self.on_show_config(porcelain).await?;
}
crate::cli::ConfigCommand::Path => {
let path = forge_config::ConfigReader::config_path();
self.writeln(path.display().to_string())?;
}
crate::cli::ConfigCommand::Migrate => {
self.handle_config_migrate()?;
}
}
Ok(())
}
/// Rename `~/forge` to `~/.forge`.
///
/// Errors if the legacy directory does not exist, if the new directory
/// already exists, or if the rename fails.
fn handle_config_migrate(&mut self) -> Result<()> {
let home = dirs::home_dir()
.ok_or_else(|| anyhow::anyhow!("Could not determine home directory"))?;
let legacy = home.join("forge");
let new = home.join(".forge");
if !legacy.exists() {
anyhow::bail!(
"Legacy directory {} does not exist — nothing to migrate",
legacy.display()
);
}
if new.exists() {
anyhow::bail!(
"Target directory {} already exists — remove it first or migrate manually",
new.display()
);
}
std::fs::rename(&legacy, &new).map_err(|e| {
anyhow::anyhow!(
"Failed to rename {} to {}: {}",
legacy.display(),
new.display(),
e
)
})?;
self.writeln_title(TitleFormat::info("Migration Completed").sub_title(format!(
"{} → {}",
legacy.display(),
new.display()
)))?;
Ok(())
}
/// Handle config set command
async fn handle_config_set(&mut self, args: crate::cli::ConfigSetArgs) -> Result<()> {
use crate::cli::ConfigSetField;
match args.field {
ConfigSetField::Model { provider, model } => {
let provider = self.api.get_provider(&provider).await?;
self.activate_provider_with_model(provider, Some(model))
.await?;
}
ConfigSetField::Commit { provider, model } => {
// Validate provider exists and model belongs to that specific provider
let validated_model = self.validate_model(model.as_str(), Some(&provider)).await?;
let commit_config =
forge_domain::ModelConfig::new(provider.clone(), validated_model.clone());
self.api
.update_config(vec![ConfigOperation::SetCommitConfig(Some(commit_config))])
.await?;
self.writeln_title(
TitleFormat::action(validated_model.as_str())
.sub_title(format!("is now the commit model for provider '{provider}'")),
)?;
}
ConfigSetField::Suggest { provider, model } => {
// Validate provider exists and model belongs to that specific provider
let validated_model = self.validate_model(model.as_str(), Some(&provider)).await?;
let suggest_config =
forge_domain::ModelConfig::new(provider.clone(), validated_model.clone());
self.api
.update_config(vec![ConfigOperation::SetSuggestConfig(suggest_config)])
.await?;
self.writeln_title(TitleFormat::action(validated_model.as_str()).sub_title(
format!("is now the suggest model for provider '{provider}'"),
))?;
}
ConfigSetField::ReasoningEffort { effort } => {
self.api
.update_config(vec![ConfigOperation::SetReasoningEffort(effort.clone())])
.await?;
self.writeln_title(
TitleFormat::action(effort.to_string())
.sub_title("is now the reasoning effort"),
)?;
}
}
Ok(())
}
/// Handle config get command
async fn handle_config_get(&mut self, args: crate::cli::ConfigGetArgs) -> Result<()> {
use crate::cli::ConfigGetField;
match args.field {
ConfigGetField::Model => {
let model = self
.api
.get_session_config()
.await
.map(|c| c.model.as_str().to_string());
match model {
Some(v) => self.writeln(v.to_string())?,
None => self.writeln("Model: Not set")?,
}
}
ConfigGetField::Provider => {
let provider = self
.api
.get_session_config()
.await
.map(|c| c.provider.to_string());
match provider {
Some(v) => self.writeln(v.to_string())?,
None => self.writeln("Provider: Not set")?,
}
}
ConfigGetField::Commit => {
let commit_config = self.api.get_commit_config().await?;
match commit_config {
Some(config) => {
self.writeln(config.provider.as_ref())?;
self.writeln(config.model.as_str().to_string())?;
}
None => self.writeln("Commit: Not set")?,
}
}
ConfigGetField::Suggest => {
let suggest_config = self.api.get_suggest_config().await?;
match suggest_config {
Some(config) => {
self.writeln(config.provider.as_ref())?;
self.writeln(config.model.as_str().to_string())?;
}
None => self.writeln("Suggest: Not set")?,
}
}
ConfigGetField::ReasoningEffort => {
let effort = self.api.get_reasoning_effort().await?;
match effort {
Some(e) => self.writeln(e.to_string())?,
None => self.writeln("ReasoningEffort: Not set")?,
}
}
}
Ok(())
}
/// Handle prompt command - returns model and conversation stats for shell
/// integration
async fn handle_zsh_rprompt_command(&mut self) -> Option<String> {
let cid = std::env::var("_FORGE_CONVERSATION_ID")
.ok()
.filter(|text| !text.trim().is_empty())
.and_then(|str| ConversationId::from_str(str.as_str()).ok());
let agent_id = std::env::var("_FORGE_ACTIVE_AGENT")
.ok()
.filter(|text| !text.trim().is_empty())
.map(AgentId::new);
// Make IO calls in parallel
let (model_id, conversation, reasoning_effort) = tokio::join!(
self.get_agent_model(agent_id.clone()),
async {
if let Some(cid) = cid {
self.api.conversation(&cid).await.ok().flatten()
} else {
None
}
},
async { self.api.get_reasoning_effort().await.ok().flatten() }
);
// Calculate total cost including related conversations
let cost = if let Some(ref conv) = conversation {
let related_conversations = self.fetch_related_conversations(conv).await;
let all_conversations: Vec<_> = std::iter::once(conv)
.chain(related_conversations.iter())
.cloned()
.collect();
Conversation::total_cost(&all_conversations)
} else {
None
};
// Check if nerd fonts should be used (NERD_FONT or USE_NERD_FONT set to "1")
let use_nerd_font = std::env::var("NERD_FONT")
.or_else(|_| std::env::var("USE_NERD_FONT"))
.map(|val| val == "1")
.unwrap_or(true); // Default to true
// Read terminal width from COLUMNS (propagated by the zsh shell plugin)
// so the rprompt can pick a compact or full-length reasoning effort
// label. Missing or unparseable values fall back to the full-length
// form in the renderer.
let terminal_width = std::env::var("COLUMNS")
.ok()
.and_then(|s| s.parse::<usize>().ok());
let rprompt = ZshRPrompt::from_config(&self.config)
.agent(agent_id)
.model(model_id)
.token_count(conversation.and_then(|conversation| conversation.token_count()))
.cost(cost)
.reasoning_effort(reasoning_effort)
.terminal_width(terminal_width)
.use_nerd_font(use_nerd_font);
Some(rprompt.to_string())
}
/// Validates that a model exists, optionally scoped to a specific provider.
/// When `provider` is `None`, models are fetched from the default provider.
async fn validate_model(
&self,
model_str: &str,
provider: Option<&forge_domain::ProviderId>,
) -> Result<ModelId> {
let models = match provider {
None => self.api.get_models().await?,
Some(provider_id) => {
self.api
.get_all_provider_models()
.await?
.into_iter()
.find(|pm| &pm.provider_id == provider_id)
.with_context(|| {
format!("Provider '{provider_id}' not found or returned no models")
})?
.models
}
};
let model_id = ModelId::new(model_str);
models
.iter()
.find(|m| m.id == model_id)
.map(|_| model_id)
.with_context(|| {
let hints = models
.iter()
.take(10)
.map(|m| m.id.as_str())
.collect::<Vec<_>>()
.join(", ");
let suggestion = if models.len() > 10 {
format!("{hints} (and {} more)", models.len() - 10)
} else {
hints
};
format!("Model '{model_str}' not found. Available models: {suggestion}")
})
}
/// Shows the last message from a conversation
///
/// When `md` is true, the raw markdown content is printed without
/// rendering. When `md` is false, the content is rendered through the
/// markdown renderer.
///
/// # Errors
/// - If the conversation doesn't exist
/// - If the conversation has no messages
async fn on_show_last_message(&mut self, conversation: Conversation, md: bool) -> Result<()> {
let context = conversation
.context
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Conversation has no context"))?;
// Find the last assistant message
let message = context.messages.iter().rev().find_map(|msg| match &**msg {
ContextMessage::Text(TextMessage { content, role: Role::Assistant, .. }) => {
Some(content)
}
_ => None,
});
// Format and display the message using the message_display module
if let Some(message) = message {
if md {
self.writeln(message)?;
} else {
self.writeln(self.markdown.render(message))?;
}
}
Ok(())
}
async fn on_index(&mut self, path: std::path::PathBuf, init: bool) -> anyhow::Result<()> {
use forge_domain::SyncProgress;
use forge_spinner::ProgressBarManager;
// Check if auth already exists and create if needed
if !self.api.is_authenticated().await? {
self.init_forge_services().await?;
}
// When init is set, check if the workspace is already initialized
// via get_workspace_info before calling init, so we only initialize
// when a workspace does not yet exist for the given path.
if init {
let workspace_info = self.api.get_workspace_info(path.clone()).await?;
if workspace_info.is_none() {
self.on_workspace_init(path.clone(), false).await?;
// If the workspace still does not exist after init (e.g. user
// declined the consent prompt), abort the sync.
let workspace_info = self.api.get_workspace_info(path.clone()).await?;
if workspace_info.is_none() {
return Ok(());
}
}
}
let mut stream = self.api.sync_workspace(path.clone()).await?;
let mut progress_bar = ProgressBarManager::default();
while let Some(event) = stream.next().await {
match event {
Ok(ref progress @ SyncProgress::Completed { .. }) => {
progress_bar.set_position(100)?;
progress_bar.stop(None).await?;
if let Some(msg) = progress.message() {
self.writeln_title(TitleFormat::debug(msg))?;
}
}
Ok(ref progress @ SyncProgress::Syncing { .. }) => {
if !progress_bar.is_active() {
progress_bar.start(100, "Indexing workspace")?;
}
if let Some(msg) = progress.message() {
progress_bar.set_message(&msg)?;
}
if let Some(weight) = progress.weight() {
progress_bar.set_position(weight)?;
}
}
Ok(ref progress) => {
if let Some(msg) = progress.message() {
self.writeln_title(TitleFormat::debug(msg))?;
}
}
Err(e) => {
progress_bar.stop(None).await?;
return Err(e);
}
}
}
Ok(())
}
async fn on_query(
&mut self,
path: PathBuf,
params: forge_domain::SearchParams<'_>,
) -> anyhow::Result<()> {
self.spinner.start(Some("Searching workspace..."))?;
let results = match self.api.query_workspace(path.clone(), params).await {
Ok(results) => results,
Err(e) => {
self.spinner.stop(None)?;
return Err(e);
}
};
self.spinner.stop(None)?;
let mut info = Info::new().add_title(format!("FILES [{} RESULTS]", results.len()));
for result in results.iter() {
match &result.node {
forge_domain::NodeData::FileChunk(chunk) => {
info = info.add_key_value(
"File",
format!(
"{}:{}-{}",
chunk.file_path, chunk.start_line, chunk.end_line
),
);
}
forge_domain::NodeData::File(file) => {
info = info.add_key_value("File", format!("{} (full file)", file.file_path));
}
forge_domain::NodeData::FileRef(file_ref) => {
info =
info.add_key_value("File", format!("{} (reference)", file_ref.file_path));
}
forge_domain::NodeData::Note(note) => {
info = info.add_key_value("Note", ¬e.content);
}
forge_domain::NodeData::Task(task) => {
info = info.add_key_value("Task", &task.task);
}
}
}
self.writeln(info)?;
Ok(())
}
/// Helper function to format workspace information consistently
fn format_workspace_info(workspace: &forge_domain::WorkspaceInfo, is_active: bool) -> Info {
let updated_time = workspace
.last_updated
.map_or("NEVER".to_string(), humanize_time);
let mut info = Info::new();
let title = if is_active {
"Workspace [Current]".to_string()
} else {
"Workspace".to_string()
};
info = info.add_title(title);
info.add_key_value("ID", workspace.workspace_id.to_string())
.add_key_value("Path", workspace.working_dir.to_string())
.add_key_value("Created At", humanize_time(workspace.created_at))
.add_key_value("Updated At", updated_time)
}
async fn on_list_workspaces(&mut self, porcelain: bool) -> anyhow::Result<()> {
if !porcelain {
self.spinner.start(Some("Fetching workspaces..."))?;
}
// Fetch workspaces and current workspace info in parallel
let env = self.api.environment();
let (workspaces_result, current_workspace_result) = tokio::join!(
self.api.list_workspaces(),
self.api.get_workspace_info(env.cwd)
);
match workspaces_result {
Ok(workspaces) => {
if !porcelain {
self.spinner.stop(None)?;
}
// Get active workspace ID if current workspace info is available
let current_workspace = current_workspace_result.ok().flatten();
let active_workspace_id = current_workspace.as_ref().map(|ws| &ws.workspace_id);
// Build Info object once
let mut info = Info::new();
for workspace in &workspaces {
let is_active = active_workspace_id == Some(&workspace.workspace_id);
info = info.extend(Self::format_workspace_info(workspace, is_active));
}
// Output based on mode
if porcelain {
// Skip header row in porcelain mode (consistent with conversation list)
self.writeln(Porcelain::from(info).skip(1).drop_cols(&[0, 4, 5]))?;
} else {
self.writeln(info)?;
}
Ok(())
}
Err(e) => {
self.spinner.stop(None)?;
Err(e)
}
}
}
/// Displays workspace information for a given path.
async fn on_workspace_info(&mut self, path: std::path::PathBuf) -> anyhow::Result<()> {
self.spinner.start(Some("Fetching workspace info..."))?;
// Fetch workspace info and status in parallel
let (workspace, statuses) = tokio::try_join!(
self.api.get_workspace_info(path.clone()),
self.api.get_workspace_status(path)
)?;
self.spinner.stop(None)?;
match workspace {
Some(workspace) => {
// When viewing a specific workspace's info, it's implicitly the active one
let mut info = Self::format_workspace_info(&workspace, true);
// Add sync status summary if available
use forge_domain::SyncStatus;
let in_sync = statuses
.iter()
.filter(|s| s.status == SyncStatus::InSync)
.count();
let modified = statuses
.iter()
.filter(|s| s.status == SyncStatus::Modified)
.count();
let added = statuses
.iter()
.filter(|s| s.status == SyncStatus::New)
.count();
let deleted = statuses
.iter()
.filter(|s| s.status == SyncStatus::Deleted)
.count();
let failed = statuses
.iter()
.filter(|s| s.status == SyncStatus::Failed)
.count();
// Add sync status section
info = info.add_title("Sync Status");
info = info.add_key_value("Total Files", statuses.len().to_string());
if in_sync > 0 {
info = info.add_key_value("In Sync", in_sync.to_string());
}
if modified > 0 {
info = info.add_key_value("Modified", modified.to_string());
}
if added > 0 {
info = info.add_key_value("Added", added.to_string());
}
if deleted > 0 {
info = info.add_key_value("Deleted", deleted.to_string());
}
if failed > 0 {
info = info.add_key_value("Failed", failed.to_string());
}
self.writeln(info)
}
None => self.writeln_to_stderr(
TitleFormat::error("No workspace found")
.display()
.to_string(),
),
}
}
async fn on_delete_workspaces(&mut self, workspace_ids: Vec<String>) -> anyhow::Result<()> {
if workspace_ids.is_empty() {
anyhow::bail!("At least one workspace ID is required");
}
// Parse all workspace IDs
let parsed_ids: Vec<forge_domain::WorkspaceId> = workspace_ids
.iter()
.map(|id| {
forge_domain::WorkspaceId::from_string(id)
.with_context(|| format!("Invalid workspace ID format: {}", id))
})
.collect::<anyhow::Result<Vec<_>>>()?;
let total = parsed_ids.len();
self.spinner.start(Some(&format!(
"Deleting {} workspace{}...",
total,
if total > 1 { "s" } else { "" }
)))?;
match self.api.delete_workspaces(parsed_ids.clone()).await {
Ok(()) => {
self.spinner.stop(None)?;
for id in &parsed_ids {
self.writeln_title(TitleFormat::debug(format!(
"Successfully deleted workspace {}",
id
)))?;
}
Ok(())
}
Err(e) => {
self.spinner.stop(None)?;
Err(e)
}
}
}
/// Displays sync status for all files in the workspace.
async fn on_workspace_status(
&mut self,
path: std::path::PathBuf,
porcelain: bool,
) -> anyhow::Result<()> {
use forge_domain::SyncStatus;
if !porcelain {
self.spinner.start(Some("Checking file status..."))?;
}
let mut statuses = self.api.get_workspace_status(path.clone()).await?;
statuses.sort_by(|a, b| a.status.cmp(&b.status));
if !porcelain {
self.spinner.stop(None)?;
}
// Calculate out of sync count
let out_of_sync = statuses
.iter()
.filter(|s| {
s.status == SyncStatus::Modified
|| s.status == SyncStatus::New
|| s.status == SyncStatus::Deleted
|| s.status == SyncStatus::Failed
})
.count();
// When all files are in sync, show a simple log message
if out_of_sync == 0 {
if porcelain {
// In porcelain mode, output empty result
self.writeln(
Porcelain::from(Info::new())
.into_long()
.set_headers(["STATUS", "FILE"])
.uppercase_headers(),
)?;
} else {
// Show log info message when all files are in sync
self.writeln_title(TitleFormat::info(format!(
"All {} files are in sync",
statuses.len()
)))?;
}
return Ok(());
}
// Build file list info only when there are files out of sync
let mut info = Info::new().add_title(format!("File Status [{} out of sync]", out_of_sync));
// Add file list (skip in-sync files)
for (status, label) in statuses.iter().filter_map(|status| match status.status {
SyncStatus::InSync => None,
SyncStatus::Modified => Some((status, "modified")),
SyncStatus::New => Some((status, "added")),
SyncStatus::Deleted => Some((status, "deleted")),
SyncStatus::Failed => Some((status, "failed")),
}) {
info = info.add_key_value(&status.path, label);
}
// Output based on mode
if porcelain {
self.writeln(
Porcelain::from(info)
.into_long()
.drop_col(0)
.swap_cols(0, 1)
.set_headers(["STATUS", "FILE"])
.sort_by(&[0])
.uppercase_headers(),
)?;
} else {
self.writeln(info)?;
}
Ok(())
}
/// Initialize workspace for a directory without syncing files
async fn on_workspace_init(
&mut self,
path: std::path::PathBuf,
yes: bool,
) -> anyhow::Result<()> {
// Ask for user consent before syncing and sharing directory contents
// with the ForgeCode Service.
let display_path = path.display().to_string();
let confirmed = if yes {
Some(true)
} else {
ForgeWidget::confirm(format!(
"This will sync and share the contents of '{}' with ForgeCode Services. Do you wish to continue?",
display_path
))
.with_default(true)
.prompt()?
};
if !confirmed.unwrap_or(false) {
self.writeln_title(TitleFormat::info("Workspace initialization cancelled"))?;
return Ok(());
}
// Check if auth already exists and create if needed
if !self.api.is_authenticated().await? {
self.init_forge_services().await?;
}
self.spinner.start(Some("Initializing workspace"))?;
let workspace_id = self.api.init_workspace(path.clone()).await?;
self.spinner.stop(None)?;
self.writeln_title(
TitleFormat::info("Workspace initialized successfully")
.sub_title(format!("{}", workspace_id)),
)?;
Ok(())
}
/// Handle credential migration
async fn handle_migrate_credentials(&mut self) -> Result<()> {
// Perform the migration
self.spinner.start(Some("Migrating credentials"))?;
let result = self.api.migrate_env_credentials().await?;
self.spinner.stop(None)?;
// Display results based on whether migration occurred
if let Some(result) = result {
self.writeln_title(
TitleFormat::warning("Forge no longer reads API keys from environment variables.")
.sub_title("Learn more: https://forgecode.dev/docs/custom-providers/"),
)?;
let count = result.migrated_providers.len();
let message = if count == 1 {
"Migrated 1 provider from environment variables".to_string()
} else {
format!("Migrated {count} providers from environment variables")
};
self.writeln_title(TitleFormat::info(message))?;
}
Ok(())
}
/// Silently install VS Code extension if in VS Code and extension not
/// installed.
/// NOTE: This is a non-cancellable and a slow task. We should only run this
/// if the user has provided a prompt because that is guaranteed to run for
/// at least a few seconds.
fn install_vscode_extension(&self) {
tokio::task::spawn_blocking(|| {
if crate::vscode::should_install_extension() {
let _ = crate::vscode::install_extension();
}
});
}
}
#[cfg(test)]
mod tests {
// Note: Tests for confirm_delete_conversation are disabled because
// ForgeSelect::confirm is not easily mockable in the current
// architecture. The functionality is tested through integration tests
// instead.
}
|