File size: 407,575 Bytes
fcfabd3 | 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 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 | // Written by Claude Code 2.1.273.
// Claude Code function hooks: the plugin API's TypeScript declarations.
//
// EARLY ACCESS: this surface may change between releases without notice.
// Written by `/plugin-types`; regenerate with that command after an update
// rather than editing. The first line names the Claude Code version that
// wrote it. TypeScript 5.4 or newer reads it.
//
// What is here: the module a hooks module may import types from,
// import type { Register, On, EngineInterface } from 'claude-code'
// (at run time the import is empty), and the globals a hooks module has:
// `h` and `Fragment` (what JSX compiles against), the JSX namespace, and
// the environment's web APIs (URL, TextEncoder, AbortController,
// crypto.subtle, ...). A hooks module runs in an environment of its own:
// no DOM, no Node. The elements a render hook draws with (`Box`, `Text`,
// `Button`, ...) are not globals: they come from the surface's table,
// const { Box, Text } = $.ui.resolve(e)
//
// Also here: 'claude-code/testing', the kit a plugin's *.test.ts and
// *.test.tsx files import under `claude plugin test <dir>`, which runs each
// in an environment like the one a plugin's hooks run in (no fs, network or
// process), the plugin loaded from the folder by the engine's own host:
// `test(name, async ($, on) => { ... })`, where `$` is the engine's own
// and the hooks `on` registers sit beneath every plugin; with describe,
// expect, tier, and `mock`, whose clock, store and env answer those nouns
// beneath the plugins from memory.
//
// Typing a plugin against it:
// export const register: Register = (on, options) => { ... }
// or, in a .js module,
// /** @type {import('claude-code').Register} */
// export const register = (on, options) => { ... }
//
// A tsconfig.json (or jsconfig.json) that fits a hooks module:
// {
// "compilerOptions": {
// "target": "es2023", "lib": ["es2023"], "types": [],
// "module": "esnext", "moduleResolution": "bundler",
// "strict": true, "noUncheckedIndexedAccess": true,
// "noEmit": true, "skipLibCheck": true,
// "jsx": "react", "jsxFactory": "h", "jsxFragmentFactory": "Fragment"
// },
// "include": [".claude/types", "hooks", "tests"]
// }
// ".claude/types" is where /plugin-types writes this file and, beside it,
// claude-code-mcp.d.ts and claude-code-plugins.d.ts, the index of the
// enabled plugins' type contracts, each copied to claude-code-plugins/
// <plugin>.d.ts: what a plugin adds to `$` in engine.create, so a plugin
// you depend on is typed with nothing copied (the include above takes the
// whole folder). "hooks" is the plugin's hooks/ folder and "tests" its test
// files. `lib` names no DOM: the environment has none, and its `Text`
// would shadow the element.
//
// A plugin that adds a noun to `$` ships its own contract: a .d.ts its
// plugin.json names as "types", exporting the noun's types at its top level
// and declaring the noun on the engine's interface,
// export type Topo = { ... }
// declare module 'claude-code' {
// interface EngineInterface { topo: Topo }
// }
// with no import or reference, its exported names led by the noun's
// PascalCase name; the plugin's own hooks module imports them from it.
declare module 'claude-code' {
/**
* What an Agent call a plugin raised (`$.tool.call({ tool: "Agent", ... })`)
* answers as `result` once the agent settles; `text` is its final answer.
*
* A plugin's spawn always runs in the background, so the call resolves with
* this record and not the Agent tool's own (BuiltinToolResults), which is
* what a model's Agent call carries at `tool.call`.
*/
export type AgentCallRecord = {
/**
* The spawned agent's id, as `$.agent.list()` names it.
*/
agentId: string;
/**
* The model the agent resolved to, when one is known.
*/
resolvedModel?: string;
};
/**
* One agent loop of this session as `$.agent.list()` returns it: a subagent
* or an in-process teammate.
*/
export type AgentInfo = {
/**
* The agent's id: the same string its loop's `tool.call` events carry as
* `agentId`, and a spawn inside it as `parentAgentId`.
*/
id: string;
/**
* Its row's label.
*/
description: string;
/**
* The agent definition it runs as (`general-purpose`, `Explore`, ...), or
* `teammate` for an in-process teammate.
*/
type: string;
/**
* `running`, `completed`, `failed`, `killed`, or another of the engine's task
* statuses.
*/
status: string;
/**
* The id of the subagent whose loop spawned it; absent when the main loop
* did.
*/
parentId?: string;
/**
* The plugin whose `$.agent.spawn` (or Agent `$.tool.call`) started it;
* absent when the model or the person did.
*
* The origin axis: which plugin caused it, whichever loop that hook ran in.
*/
spawnedBy?: string;
/**
* What SendMessage addresses it by (`Agent({ name })`, or the engine's own
* for a background agent), when it has one; not `description` or `type`.
*/
name?: string;
};
/**
* Which model loop an event happened in: the loop's agent id inside a
* subagent's or a teammate's loop, absent on the main loop.
*
* The agent axis, not the origin axis: `next.origin` names the plugin whose
* hook frame caused the dispatch (the recursion skip), whichever loop it ran
* in; `agentId` names the loop, whoever caused the call.
*/
export type AgentLoop = {
/**
* The id of the loop this call runs in: for a subagent or a teammate, the
* `id` `$.agent.list()` gives it; absent on the main loop.
*
* A workflow's agents and the engine's own forks (compaction, memory) carry
* ids no list names. Pinned: a different value is refused, one left out is
* kept. Which loop, not which plugin caused it (that is `next.origin`).
*/
agentId?: string;
};
/**
* The input of `agent.offer`: one agent type, at the moment the engine
* offers it to the model.
*
* Listed for the model (the agent listing) or named by it at dispatch
* (`subagent_type`): the same event at each.
*/
export type AgentOfferInput = {
/**
* Which type (`Explore`, `Plan`, a plugin's agent); the key a matcher
* narrows on.
*/
agent: string;
/**
* Its listing line's text as the definition states it (`whenToUse`).
*/
description: string;
/**
* Where the definition came from (`built-in`, `plugin`, a settings
* source), so a matcher tells a built-in from a user's agent of its name.
*/
source: string;
/**
* Who provides this agent: the plugin and its tier; `{ plugin: "engine",
* tier: "core" }` for a built-in. Pinned: a rewrite is refused.
*/
provider: Origin;
};
/**
* What an `agent.offer` hook returns: whether the model is offered the agent
* type, in its listing and at dispatch.
*/
export type AgentOfferResult = {
isOffered: boolean;
};
/**
* `agent.spawn`'s input as the call takes it: what the Agent tool's caller
* says; the engine fills the rest.
*
* A call's spawn runs in the background: it resolves once the subagent
* started, and nothing holds it in the foreground.
*/
export type AgentSpawnArgs = Pick<AgentSpawnInput, 'prompt'> & Partial<Pick<AgentSpawnInput, 'description' | 'subagentType' | 'model' | 'name' | 'cwd'>>;
/**
* The input of `agent.spawn`: what the Agent tool decided about the
* subagent it is about to start, before its model is resolved.
*
* A hook rewrites content (prompt, description, subagentType, model,
* background, cwd), read back as the tool's parameters; tool_use_id, name,
* fork, parentModel, permissionMode, parentAgentId and provider are pinned.
*/
export type AgentSpawnInput = {
/**
* The Agent tool call this spawn belongs to (for `$.ui.notice`). Pinned:
* the spawn's identity.
*/
tool_use_id: string;
/**
* The task the subagent is given: the Agent tool's `prompt` parameter. A
* rewrite is the prompt the subagent runs with.
*/
prompt: string;
/**
* The Agent tool's short `description` of the task (a few words). A rewrite
* is what the task shows as.
*/
description: string;
/**
* The resolved agent type (`general-purpose`, `Explore`, a plugin's agent,
* `fork`). A rewrite names another agent this call can dispatch, exactly.
*
* That definition is the one spawned; a name matching none refuses the
* spawn, and a fork dispatches no other.
*/
subagentType: string;
/**
* Who provides this agent: the plugin and its tier; `{ plugin: "engine",
* tier: "core" }` for a built-in. Pinned with the spawn's identity.
*/
provider: Origin;
/**
* The Agent tool's `model` parameter as given, an alias (`haiku`) or a
* full id; undefined lets the agent's own model, then the parent's, decide.
*
* Ignored for forks, which always inherit. A hook sets this to pick the
* subagent's model.
*/
model?: string;
/**
* The parent's effective model, what `inherit` resolves to. Pinned: a fact
* of the parent (set `model` to change what the subagent runs on).
*/
parentModel: string;
/**
* The id of the loop the spawn happens in (its `tool.call` `agentId`; for a
* subagent or teammate its `$.agent.list()` id); absent from main.
*
* Pinned: a different value is refused, one left out is kept. The agent
* axis, not the origin: `next.origin` names the plugin whose hook frame
* caused the spawn, this names the model loop it happened in.
*/
parentAgentId?: string;
/**
* The parent's permission mode (`default`, `acceptEdits`, `plan`, ...), which
* the subagent inherits. Pinned: a fact of the parent.
*/
permissionMode?: string;
/**
* True when the subagent will run in the background (or remotely). A
* rewrite is read back as the call's `run_in_background`.
*
* The agent's own definition and remote isolation can still force it on,
* and disabled background tasks force it off.
*/
background: boolean;
/**
* True for a fork of the parent: it inherits the parent's context and model,
* and `model` is ignored. Pinned: the spawn's identity.
*/
fork: boolean;
/**
* Given by the call (`Agent({ name })`, addressable by SendMessage);
* undefined when unnamed. Pinned: the address the parent routes by.
*/
name?: string;
/**
* The directory the subagent runs in when the call set one (`cwd`); undefined
* means the parent's. A rewrite is where the subagent runs.
*/
cwd?: string;
};
/**
* What an `agent.spawn` hook returns and what `next(e)` resolves to: the
* started subagent's `{ model, agentId }`, or `{ deny: reason }`, refusing it.
*
* It and `$.agent.spawn(input)` resolve once the subagent started; its answer
* is its own `turn.complete`, carrying this `agentId`. Keep the id and set
* `got[agentId]` to what waits; a `turn.complete` hook resolves it:
*
* @example
* on("turn.complete", ($, e, next) => (got[e.agentId]?.(e.answer), next(e)))
*/
export type AgentSpawnResult = {
/**
* What the subagent runs on: from core the resolved id; from a hook an
* alias (`haiku`) or an id.
*/
model: string;
/**
* The started subagent's id: the same string its loop's `tool.call`
* events carry as `agentId` and `$.agent.list()` lists it by.
*
* Set by core; a hook that answers without `next` started none.
*/
agentId?: string;
deny?: undefined;
} | {
/**
* Refuses the spawn, so nothing starts; the model sees the text as the
* Agent tool's error.
*/
deny: string;
model?: undefined;
agentId?: undefined;
};
/**
* The hook `on("*", hook)` takes: it runs on every event, plugin nouns no
* declaration names included, so `e` is `unknown` and `next` is StarNext.
*
* Until `next.is(pattern, e)` narrows `e`, all a hook can do with it is pass
* it on, time it, log it, or fail it; once narrowed it is an ordinary hook on
* those events.
*
* @param $ the engine interface; at `engine.create` the empty table, so a hook
* that reads `$` tests `next.is("engine.create", e)` first
*/
export type AnyEventHook = ($: EngineInterface, e: unknown, next: StarNext) => unknown;
/**
* Every key of every variant, index signatures included.
*/
type AnyKeyOf<I> = I extends unknown ? keyof I : never;
/**
* The argument of event `N`: `e` in its hooks, and what its call takes. For a
* union of names, the union of their arguments.
*/
export type Args<N extends EventName = EventName> = EventOf[N];
/**
* Options of `$.ui.ask`.
*/
export type AskOptions = {
/**
* 2-4 option labels; fewer than two are padded with Yes/No; free text is the
* dialog's Other.
*/
options?: readonly string[];
/**
* A short chip beside the question (`Approach`, 12 characters at most).
*/
header?: string;
/**
* Allow several options; the answer comes back comma-joined.
*/
multiSelect?: true;
};
/**
* The input of `attribution.text`: one text the engine asks the model to
* write into a commit or a pull request, at the moment it is composed.
*
* Composed for the Bash description, the commit skills, a PR's body, the
* pre-ship mandate and the commit gate's deny: the same event at each.
*/
export type AttributionTextInput = {
/**
* Which text (`commit`, `pr`, `exemption`, `remedy`); the key a matcher
* narrows on.
*/
kind: AttributionTextKind;
/**
* As the engine composed it, the settings applied.
*/
text: string;
};
/**
* Which git text `attribution.text` carries: the commit trailer, the PR
* footer, the mandate's or the commit gate's sentence naming the exemption.
*/
export type AttributionTextKind = 'commit' | 'pr' | 'exemption' | 'remedy';
/**
* What an `attribution.text` hook returns: the text the model reads in
* that place.
*/
export type AttributionTextResult = {
text: string;
};
/**
* What `$.audio.play` plays: a URL the engine fetches, or the bytes.
*/
export type AudioClip = {
/**
* A file of the calling plugin's own, relative to the plugin's
* directory (`fx/open.wav`); no `.`, no leading slash.
*
* The engine resolves it and loads the file from disk.
*/
asset: string;
url?: undefined;
base64?: undefined;
mime?: undefined;
} | {
/**
* The clip's URL; the engine fetches it (never the plugin).
*/
url: string;
asset?: undefined;
base64?: undefined;
mime?: undefined;
} | {
/**
* The clip's bytes, base64.
*/
base64: string;
/**
* What the bytes are (`audio/mpeg`, `audio/wav`).
*/
mime: string;
asset?: undefined;
url?: undefined;
};
type BackgroundTaskSummary = {
id: string;
/**
* Friendly task-type label (e.g. 'shell', 'subagent', 'monitor', 'workflow'). Falls back to the raw discriminant for unknown types.
*/
type: string;
status: string;
/**
* Free-text description. Capped at 1000 chars; clipped values append an in-string "... [+N chars]" marker.
*/
description: string;
/**
* Shell command line. Only present for 'shell' tasks. Capped at 1000 chars with the same "... [+N chars]" marker.
*/
command?: string;
/**
* Subagent type name. Only present for 'subagent' tasks.
*/
agent_type?: string;
/**
* MCP server name. Only present for 'monitor' / 'MCP task' tasks.
*/
server?: string;
/**
* MCP tool name. Only present for 'monitor' / 'MCP task' tasks.
*/
tool?: string;
/**
* Workflow name. Only present for 'workflow' tasks.
*/
name?: string;
};
type BaseHookInput = {
session_id: string;
transcript_path: string;
cwd: string;
/**
* UUID correlating a user prompt with all subsequent events until the next prompt. Same value emitted on OpenTelemetry events as the `prompt.id` attribute, so hook output can be joined to OTel events at prompt grain. Absent until the first user input of the process lifetime.
*/
prompt_id?: string;
permission_mode?: string;
/**
* Subagent identifier. Present only when the hook fires from within a subagent (e.g., a tool called by an AgentTool worker). Absent for the main thread, even in --agent sessions. Use this field (not agent_type) to distinguish subagent calls from main-thread calls.
*/
agent_id?: string;
/**
* Agent type name (e.g., "general-purpose", "code-reviewer"). Present when the hook fires from within a subagent (alongside agent_id), or on the main thread of a session started with --agent (without agent_id).
*/
agent_type?: string;
/**
* Reasoning effort applied to the current turn. Same shape as StatusLineCommandInput.effort. Present for hooks that fire within a tool-use context (PreToolUse, PostToolUse, Stop, SubagentStop, etc.) on a model that supports the effort parameter; absent for session-lifecycle hooks and models without effort support.
*/
effort?: {
/**
* Active effort level for the current turn (e.g., "low", "medium", "high", "xhigh", "max"), after any silent downgrade for the selected model. Also exposed to hook commands and Bash as the CLAUDE_EFFORT env var.
*/
level: string;
};
};
/**
* The `Box` props a `hover` may override, none of which moves layout, and
* `scope`, which names the hover group the Box joins instead of a style.
*
* `display` is `"flex"` alone, on a Box drawn `display: "none"` inside a
* visible keyed Box, and never beside a `scope` (a group lit from another
* site would move what the pointer is over); `borderStyle` only restyles.
*/
export type BoxHoverProps = {
/**
* Names a hover group of this plugin's: every element it draws with the
* same `scope`, in any site on the surface, lights while any is hovered.
*
* A Pane row and a mark on a transcript message can share one. Another
* plugin's elements under the same string are a different group. One to
* 64 characters, no control characters; no keyed Box needed; no hook runs.
*/
scope?: string;
borderStyle?: string;
borderColor?: string;
borderDimColor?: boolean;
backgroundColor?: string;
display?: 'flex';
};
/**
* The props of `Box`: the layout, margin, padding and border props of Ink's
* Box a tree may set, and the two of hover.
*/
export type BoxProps = {
/**
* Makes the Box a hover scope: while the pointer is anywhere over it, its
* own `hover` and that of every element beneath it apply.
*
* A nested Box with a `key` of its own scopes what is beneath it. A key a
* sibling Box already took, or one that is no plain string, names no
* scope: the Box draws, and hovers beneath it stay inert.
*/
key?: string;
/**
* Style overrides applied by the surface while the pointer is over the
* nearest keyed `Box`, this one included, or, given a `scope`, its group.
*
* Never a layout change; no hook runs and nothing crosses to the plugin.
* To reveal on hover, draw a Box `display: "none"` with `hover: { display:
* "flex" }` inside a visible keyed Box; a scoped hover never reveals.
*/
hover?: BoxHoverProps;
flexDirection?: 'row' | 'column' | 'row-reverse' | 'column-reverse';
flexGrow?: number;
flexShrink?: number;
flexWrap?: 'nowrap' | 'wrap' | 'wrap-reverse';
alignItems?: 'flex-start' | 'center' | 'flex-end' | 'stretch';
alignSelf?: 'flex-start' | 'center' | 'flex-end' | 'auto';
justifyContent?: 'flex-start' | 'center' | 'flex-end' | 'space-between' | 'space-around' | 'space-evenly';
gap?: number;
columnGap?: number;
rowGap?: number;
width?: number | string;
height?: number | string;
minWidth?: number | string;
minHeight?: number | string;
margin?: number;
marginX?: number;
marginY?: number;
marginTop?: number;
marginBottom?: number;
marginLeft?: number;
marginRight?: number;
padding?: number;
paddingX?: number;
paddingY?: number;
paddingTop?: number;
paddingBottom?: number;
paddingLeft?: number;
paddingRight?: number;
borderStyle?: string;
borderColor?: string;
borderDimColor?: boolean;
backgroundColor?: string;
overflow?: 'visible' | 'hidden';
display?: 'flex' | 'none';
};
/**
* One variant per built-in tool; with none in the table (a plugin author's
* project before `/plugin-types` ran), one loose variant over every name.
*/
export type BuiltinToolCallInput = [BuiltinToolName] extends [never] ? BuiltinToolCallInputFallback : {
[N in BuiltinToolName]: ToolInputOf<N, BuiltinToolInputs[N]>;
}[BuiltinToolName];
/**
* The built-in branch's answer when no built-in tool is declared: every
* name, its args unconstrained.
*/
type BuiltinToolCallInputFallback = {
/**
* The name of the tool being called (`Bash`); comparing it narrows `e` once
* the table has entries. Reserved: a rewrite of it is ignored by core.
*/
tool: string;
/**
* The tool_use block's id: the same at every event of the call and in
* `$.ui.notice`. Reserved: a rewrite of it is ignored by core.
*/
tool_use_id: string;
[argument: string]: unknown;
};
/**
* The arguments of each built-in tool by name, for declaration merging;
* empty until a declaration file adds entries, then `e.tool === "Bash"`
* narrows `e` to Bash's arguments.
*
* `/plugin-types` writes this build's set beneath the engine's declarations
* (claude-code.d.ts), from each tool's input schema.
*
* @example
* interface BuiltinToolInputs { Bash: { command: string; timeout?: number } }
*/
export interface BuiltinToolInputs {
}
/**
* The names of the built-in tools.
*/
export type BuiltinToolName = keyof BuiltinToolInputs & string;
/**
* The structured result of each built-in tool by name, for declaration
* merging; empty until a declaration file adds entries, then after
* `e.tool === "Bash"` the `result` of `next(e)` is Bash's record.
*
* `/plugin-types` writes this build's set beneath the engine's declarations
* (claude-code.d.ts), from each tool's output schema; a tool without one is
* `unknown`.
*
* @example
* interface BuiltinToolResults { Bash: { stdout: string; stderr: string } }
*/
export interface BuiltinToolResults {
}
/**
* The props of `Button`, every surface's pressable leaf: an address, a
* label, the closure a press runs, and the label styles a hover overrides.
*
* The terminal draws `[ label ]` (when `plain`, `1: label` or the label
* alone), a desktop a native button; a click, a `hotkey`, the chord for its
* `action`, or Enter under the focus raises `ui.press`, its bottom `onPress`.
*/
export type ButtonProps = {
/**
* The element's address: `e.element` at `ui.press`, what a matcher names.
* Defaults to the label.
*/
key?: string;
/**
* The text drawn on the button; or the one string child.
*/
label?: string;
/**
* One digit (`"1"`) or one lowercase letter (`"w"`) that presses it where
* the site honours one (the `AbovePrompt` band); anything else is refused.
*
* A digit presses from an empty composer; a digit or letter presses on
* keydown while one of the band's Buttons has the focus (Shift+w matches
* `"w"`; held keys repeat). Of two Buttons on one hotkey the later wins.
*/
hotkey?: string;
/**
* An engine keybinding action (`"app:cycleDiffBase"`) whose chord, as the
* person bound it, presses this from the prompt; unknown names refused.
*
* Chords, or a modified key Global or an active context binds, on the
* terminal while mounted, no dialog up and no engine handler of the action
* mounted; a pane's over the band's over another's, then the last drawn.
*/
action?: string;
/**
* Drawn without chrome: the hotkey in the accent color, a colon, the
* label (`1: Yes`), as a survey's row reads; no `hotkey`, the label alone.
*
* A one-glyph label (`'\u{1F50A}'`, a speaker) is then a control by
* itself: the focus and the pointer still invert it, `dimColor` and `hover`
* still apply. A desktop draws its native button either way.
*/
plain?: true;
/**
* The label drawn dim at rest, as `Text`'s `dimColor`, and at full strength
* under the pointer or the focus: a secondary control, a path in a list.
*/
dimColor?: boolean;
/**
* The site's focus ring starts here when the site takes the keyboard,
* instead of on nothing, as the DOM's `autofocus`: Enter acts on it at once.
*
* A pane opened with `focus`, or the person's focus chord or click, is the
* take. Of several in one site the first drawn wins; it raises `ui.focus`,
* origin this plugin. A ring the person has moved stays where it was put.
*/
autoFocus?: true;
/**
* Label style overrides (the `Text` set) applied by the surface while the
* nearest enclosing keyed `Box`, or given a `scope` its group, is hovered.
*
* No hook runs and nothing crosses to the plugin; under the pointer itself
* the button inverts as it always has. Refused outside a keyed Box unless
* it names a `scope`.
*/
hover?: TextHoverProps;
/**
* What the press runs, in the plugin's own environment: the bottom of the
* `ui.press` chain. The host holds only a handle, for the drawing's life.
*/
onPress: () => void;
};
/**
* The handler `on(...).catch(handler)` takes for a hook of type `F`: the
* hook's `($, e, next)`, run afresh when it throws, misreturns or overruns.
*
* `next` carries `error` and `called` (Caught) and is replay-safe; a return
* within the grace is the hook's result, `undefined` the hook absent. On a
* streaming event the handler is a generator too, continuing the stream.
*/
export type CatchHandler<F> = F extends ($: infer D, e: infer E, next: infer N) => infer R ? [R] extends [AsyncGenerator<unknown, unknown, unknown>] ? ($: D, e: E, next: N & Caught) => R : ($: D, e: E, next: N & Caught) => R | undefined | Promise<Awaited<R> | undefined> : never;
/**
* What `next` carries into a `.catch` handler and nowhere else: why the
* hook failed, and whether it had called `next` before it did.
*
* There `next` is replay-safe: when `called`, `next(e)` resolves to what the
* hook's last call settled to, nothing beneath running again, the argument
* unread; when not, it runs the hooks beneath once and a later call replays.
*/
export type Caught = {
/**
* Why the hook failed (HookFailure); undefined on an ordinary hook's
* `next`, so its presence says a handler is running.
*/
readonly error: HookFailure;
/**
* True when the failed hook had called `next()` or `next.to()` at least
* once, settled or in flight; the handler runs once that call settled.
*/
readonly called: boolean;
};
/**
* What a hook on streaming event `N` yields, and what its `next(e)` yields
* to it (ChunkOf by name).
*/
export type Chunk<N extends StreamingEventName = StreamingEventName> = ChunkOf[N];
/**
* The chunk type of each streaming event, by name: what its stream yields.
*/
export type ChunkOf = {
/**
* One piece of the model's response (TurnStepChunk).
*/
'turn.step': TurnStepChunk;
};
/**
* What every `turn.step` chunk may carry: the engine's handle on the item
* of its own stream the chunk was read off, absent on a chunk a hook made.
*
* A hook that passes a chunk on, or rewrites it by spreading it, keeps the
* handle, and whatever it left unchanged reaches the engine as the engine
* streamed it; a chunk built afresh has none and is taken at its word.
*/
type ChunkRef = {
/**
* The engine's handle on its own streamed item; opaque, this step's only.
*/
ref?: number;
};
/**
* The name of a classic hook event as a function-hooks event: the settings
* hook's own name under `classic` (`classic.Stop`, `classic.PreToolUse`).
*/
export type ClassicEventName = `classic.${ClassicHookEvent}`;
/**
* The classic (settings) hook events, one per classic event name: `e` is
* what the classic hook receives on stdin for that event.
*
* The chain is [managed settings hooks, ...hooks modules, the other settings
* hooks as core], so a managed block ends it above every module. In shape
* `classic.PreToolUse` alone differs: its `e` is ToolCallEnvelope, no more.
*/
export type ClassicEventOf = {
[E in ClassicHookEvent as `classic.${E}`]: E extends 'PreToolUse' ? ToolCallEnvelope : ClassicHookInputs[E];
};
/**
* The name of a classic hook event: `PreToolUse`, `Stop`, and the rest.
*/
export type ClassicHookEvent = HookInput['hook_event_name'];
/**
* What a classic hook receives on stdin for each event, by event name: the
* Agent SDK's `<Event>HookInput`.
*/
export type ClassicHookInputs = {
[I in HookInput as I['hook_event_name']]: I;
};
/**
* Everything a classic hook event's answer can carry, named as the classic
* hook's JSON output names it; each event reads its subset (ClassicResultOf).
*
* The settings hooks below fold into one of these (last write wins, contexts
* concatenate); a hooks module returns `next(e)`, a copy with fields changed,
* or its own. A field of the wrong shape fails the hook, which is skipped.
*/
export type ClassicResult = {
/**
* `decision: "block"` with this text as `reason` (a command hook's exit
* code 2): the event's block, veto or re-prompt.
*/
block?: string;
/**
* `continue: false`: the session stops after this event.
*/
preventContinuation?: true;
/**
* Shown when `preventContinuation` stops the session (`stopReason`).
*/
stopReason?: string;
/**
* `hookSpecificOutput.additionalContext`, one entry per hook: text handed
* to the model with the event.
*/
additionalContext?: string[];
/**
* `hookSpecificOutput.sessionTitle` (UserPromptSubmit, SessionStart).
*/
sessionTitle?: string;
/**
* `hookSpecificOutput.suppressOriginalPrompt` (UserPromptSubmit,
* UserPromptExpansion).
*/
suppressOriginalPrompt?: true;
/**
* `hookSpecificOutput.initialUserMessage` (SessionStart).
*/
initialUserMessage?: string;
/**
* `hookSpecificOutput.watchPaths` (SessionStart).
*/
watchPaths?: string[];
/**
* `hookSpecificOutput.reloadSkills` (SessionStart).
*/
reloadSkills?: true;
/**
* `hookSpecificOutput.permissionDecision` (PreModelSwitch).
*/
permissionDecision?: 'allow' | 'deny' | 'ask';
/**
* `hookSpecificOutput.permissionDecisionReason` (PreModelSwitch).
*/
permissionDecisionReason?: string;
/**
* `hookSpecificOutput.decision` (PermissionRequest).
*/
decision?: PermissionRequestDecision;
/**
* `hookSpecificOutput.updatedToolOutput` (PostToolUse): replaces what the
* model sees of the tool's result.
*/
updatedToolOutput?: unknown;
/**
* `hookSpecificOutput.updatedMCPToolOutput` (PostToolUse, MCP tools only).
*/
updatedMCPToolOutput?: unknown;
/**
* `hookSpecificOutput.retry` (PermissionDenied).
*/
retry?: true;
/**
* `hookSpecificOutput.displayContent` (MessageDisplay).
*/
displayContent?: string;
/**
* `hookSpecificOutput.worktreePath` (WorktreeCreate; a command hook prints
* it): the worktree the hook created, absolute or relative to its cwd.
*
* Left unset, the session creates its git worktree as it would unhooked.
*/
worktreePath?: string;
};
/**
* The event-specific fields of ClassicResult each classic event reads (its
* `hookSpecificOutput`), by event; an event absent here reads none of them.
*
* `block`, `preventContinuation` and `stopReason` are every event's.
*/
export type ClassicResultFields = {
UserPromptSubmit: 'additionalContext' | 'sessionTitle' | 'suppressOriginalPrompt';
UserPromptExpansion: 'additionalContext' | 'suppressOriginalPrompt';
SessionStart: 'additionalContext' | 'initialUserMessage' | 'sessionTitle' | 'watchPaths' | 'reloadSkills';
Setup: 'additionalContext';
PreModelSwitch: 'permissionDecision' | 'permissionDecisionReason';
PostModelSwitch: 'additionalContext';
SubagentStart: 'additionalContext';
PostToolUse: 'additionalContext' | 'updatedToolOutput' | 'updatedMCPToolOutput';
PostToolUseFailure: 'additionalContext';
PostToolBatch: 'additionalContext';
Stop: 'additionalContext';
SubagentStop: 'additionalContext';
PermissionDenied: 'retry';
PermissionRequest: 'decision';
MessageDisplay: 'displayContent';
WorktreeCreate: 'worktreePath';
};
/**
* What each classic hook event's hook returns and its `next(e)` resolves to:
* the event's own subset of ClassicResult.
*
* `classic.PreToolUse` keeps its `allow` / `ask` / `deny` result
* (PreToolUseResult).
*/
export type ClassicResultOf = {
[E in ClassicHookEvent as `classic.${E}`]: E extends 'PreToolUse' ? PreToolUseResult : Pick<ClassicResult, 'block' | 'preventContinuation' | 'stopReason' | (E extends keyof ClassicResultFields ? ClassicResultFields[E] : never)>;
};
/**
* Options of `$.model.classify`.
*/
export type ClassifyOptions = {
/**
* An alias (`haiku`) or a full model id; default the engine's small fast
* model.
*/
model?: string;
};
/**
* The element table a surface module draws with, `surface.elements`: the
* terminal's (Elements) less `Client` (none nests) and `Raster` (needs `$`).
*
* What `$.ui.resolve(e)` is to a hooks module, with no `$` and no hook
* between: `const { Box, Text } = surface.elements`, then `<Box>`. A Button,
* Input or Select keeps its handler here and still raises `ui.press` etc.
*/
export type ClientElements = Omit<Elements['terminal'], 'Client' | 'Raster'>;
/**
* One key the person pressed while a `Client` had the focus, as
* `surface.onKey` hands it. Escape never arrives: it returns the focus.
*/
export type ClientKeyEvent = {
/**
* A special key's name (`up`, `down`, `left`, `right`, `return`, `tab`,
* `backspace`, `delete`, `pageup`, `home`, ...) or the character typed.
*/
key: string;
/**
* Modifier keys held with it, each present only when true.
*/
ctrl?: true;
shift?: true;
meta?: true;
};
/**
* The component a surface module exports (default, or its one PascalCase
* export): from props and surface to the tree drawn (no nested `Client`).
*
* Runs in the plugin's surface environment on the drawing thread, under a
* time budget per call; a throw or an overrun unmounts the instance and
* draws one line naming the plugin and the module in its place.
*/
export type ClientModule<P extends JsonValue = JsonValue, S = unknown> = (props: P, surface: ClientSurface<S>) => RenderElement;
/**
* One pointer event over a `Client`'s region, as `surface.onPointer` hands
* it: cell coordinates relative to the region's top-left corner.
*
* After a `down` in the region the instance holds the pointer until the
* `up`: every `move` reaches it, past the edges too (negative, or beyond
* `columns`/`rows`), and the transcript neither selects nor scrolls.
*/
export type ClientPointerEvent = {
type: ClientPointerType;
/**
* The column under the pointer, 0 at the region's left edge; on `enter`
* and `leave`, the last column a move reported.
*/
x: number;
/**
* The row under the pointer, 0 at the region's top edge.
*/
y: number;
/**
* Which button is down (`down`, `move` while held) or came up (`up`);
* absent on a hover `move`, `enter` and `leave`.
*/
button?: 'left' | 'middle' | 'right';
/**
* Modifier keys the terminal reported held, each present only when true.
*/
shift?: true;
alt?: true;
ctrl?: true;
};
/**
* What the pointer did over a `Client`'s region: a button went down, the
* pointer moved, the button came up, or the pointer crossed the region's edge.
*/
export type ClientPointerType = 'down' | 'move' | 'up' | 'enter' | 'leave';
/**
* The props of `Client`: which of the plugin's surface modules draws here,
* under what key, with what data, in how much room.
*/
export type ClientProps = {
/**
* The instance's address within the drawing: two `Client`s of one plugin in
* one tree take two keys. What `e.element` carries at `ui.message`.
*
* The engine keeps the instance (its local state, its timers) across the
* plugin's redraws while a `Client` under this key stays in the tree.
*/
key: string;
/**
* The surface module's path, a string literal relative to this file:
* `module: "./<name>.tsx"` (or `.jsx`, `.ts`, `.js`, `.mjs`).
*
* Read off the source: a variable there is refused at load, as is a path
* outside the plugin or naming no file. Its default export draws, else
* its one PascalCase export; loaded, the tree carries the plugin's path.
*/
module: string;
/**
* Plain data (JsonValue) handed to the module function; a new value on a
* redraw reaches the running instance, its state kept.
*
* Bounded as a tree's text is; not a channel for closures.
* Typed `unknown` so a matcher over a tree stays shallow.
*/
props?: unknown;
/**
* Columns the instance's region takes: a count, or a percentage of the
* parent. Absent, the region is as wide as what the module draws.
*/
width?: number | string;
/**
* Rows the instance's region takes: a count, or a percentage of the parent.
* Absent, the region is as tall as what the module draws.
*/
height?: number | string;
/**
* How the region grows into free room along the parent's direction, as a
* Box's `flexGrow`.
*/
flexGrow?: number;
};
/**
* What a surface module's function receives as its second argument: its
* elements, the instance's local state, its region, input, clock and port.
*
* Called again (same `surface`, same `state`) on new props, after
* `setState`, and on a resize; what it returns is drawn in the region. No
* `$` here: the hooks module has it, and `post` is the way to reach it.
*/
export type ClientSurface<S = unknown> = {
/**
* The surface's element table (ClientElements), the tags the module draws
* with: `const { Box, Text } = surface.elements`. No `Client` in it.
*/
readonly elements: ClientElements;
/**
* The instance's local state: `undefined` until the first `setState`.
* Kept across the plugin's redraws; dropped with the instance.
*/
readonly state: S | undefined;
/**
* Replaces the local state and schedules one more call of the function on
* the next frame; several calls before it coalesce into one redraw.
*/
setState: (next: S) => void;
/**
* The region's width in cells, as last laid out (0 before the first
* layout).
*/
readonly columns: number;
/**
* The region's height in cells, as last laid out (0 before the first
* layout).
*/
readonly rows: number;
/**
* Calls `fn` every `ms` milliseconds on the surface's frame clock until
* the returned function is called or the instance unmounts.
*
* Start it once (while `state` is still undefined), not on every call.
*/
every: (ms: number, fn: () => void) => () => void;
/**
* Sets the instance's pointer listener (one; a later call replaces it)
* and returns what clears it. See ClientPointerEvent for capture.
*/
onPointer: (fn: (event: ClientPointerEvent) => void) => () => void;
/**
* Sets the instance's key listener (one; a later call replaces it),
* reached while a click has given it the focus; Escape returns that.
*/
onKey: (fn: (event: ClientKeyEvent) => void) => () => void;
/**
* Sends plain data to the plugin's hooks module: `e.data` of a
* `ui.message` only that plugin's hooks see, one per frame at most.
*
* A later post in the same frame replaces an undelivered one; a hook
* answering `{ props }` hands this instance its next props.
*/
post: (data: JsonValue) => void;
};
/**
* The argument of the `$.clock` waits (`sleep`, `after`, `every`): how long,
* in milliseconds, before the dispatch resolves.
*/
type ClockWait = {
/**
* The wait, a non-negative number of milliseconds.
*/
ms: number;
};
/**
* The props of `Code`, source text every surface draws with the engine's own
* highlighter: coloured tokens, a line gutter on request, or a unified diff.
*
* A leaf: no children. `source` is the element's data as a string is a
* Text's, bounded and free of control characters the same way; the colour
* on screen is the engine's, never the plugin's.
*/
export type CodeProps = {
/**
* The text drawn: source code, or under `format: 'diff'` one or more
* unified-diff hunks.
*
* At most 10000 characters; tab and newline are the only control
* characters it may hold.
*/
source: string;
/**
* A highlighter language id or alias (`typescript`, `ts`, `py`), a
* plugin-contributed grammar's included.
*
* Absent, the language is inferred from `path`; when neither resolves,
* the text is drawn plain.
*/
language?: string;
/**
* A file path the language is inferred from when `language` is absent:
* its extension or name, else a shebang on the first line.
*
* Drawn nowhere and never read: nothing touches the disk.
*/
path?: string;
/**
* The 1-based number of the first line of `source`: present, a dim
* right-aligned gutter numbers the lines from it; absent, no gutter.
*
* Ignored under `format: 'diff'`, whose hunks carry their own numbers.
*/
startLine?: number;
/**
* `'source'` (the default) draws `source` as code; `'diff'` reads it as
* unified-diff hunks and draws gutters, markers, add and remove colouring.
*
* A hunk is `@@ -a,b +c,d @@` then lines starting ` `, `+` or `-`; a
* leading `---`/`+++` pair and `\ No newline at end of file` are read
* past. A source that does not parse as hunks is refused.
*/
format?: 'source' | 'diff';
/**
* What a line wider than the room does, in Text's `wrap` vocabulary:
* `'wrap'` (the default) continues it on rows under the gutter.
*
* `'truncate-end'` cuts it at the edge with an ellipsis; Text's other
* spellings are refused, since a gutter leaves them no sense here.
*/
wrap?: 'wrap' | 'truncate-end';
};
/**
* The input of `command.describe`: how one slash command presents in the
* typeahead and `/help`, at the moment the engine lists it.
*/
export type CommandDescribeInput = {
/**
* Names the command without its slash; the key a matcher narrows on. A
* rewrite is refused.
*/
command: string;
/**
* The one-line description the menu shows, as the command declares it.
*/
description: string;
/**
* The hint drawn dim after the name (`[name]`), when the command has one.
*/
argumentHint?: string;
/**
* Whether the typeahead and `/help` leave the command out; a hidden
* command still runs when typed in full.
*/
isHidden: boolean;
/**
* Whether the command declares it runs at once when typed mid-turn,
* instead of waiting for the turn to end.
*
* One that decides per invocation reads false. Read only: not part of
* what a hook answers, and a rewrite is refused.
*/
immediate: boolean;
/**
* Who provides this command: the plugin and its tier; `{ plugin: "engine",
* tier: "core" }` for a built-in. Pinned: a rewrite is refused.
*/
provider: Origin;
};
/**
* What a `command.describe` hook returns: the description, hint and hidden
* flag the menu uses; the name, `immediate` and `provider` stay as they were.
*/
export type CommandDescribeResult = Omit<CommandDescribeInput, 'command' | 'immediate' | 'provider'>;
/**
* One slash command as `$.command.list()` returns it.
*/
export type CommandInfo = {
/**
* What the person runs it by, without the slash.
*/
name: string;
/**
* The one line the typeahead shows for it.
*/
description: string;
/**
* Where it comes from (CommandSource).
*/
source: CommandSource;
/**
* Which plugin added it, when `source` is `plugin` and the engine knows:
* the one that registered it, or whose manifest carries it.
*/
plugin?: string;
};
/**
* Where a command's answer will show: which of the terminal's two layouts
* the surface renders, and how wide it is when the command runs.
*
* A fact the engine stamps on `command.run`, so a command that draws (opens
* a pane, prints a wide table) can suit the room it has: the fullscreen
* layout docks a pane beside the transcript from 110 columns, the main
* screen places it inline above the prompt at any width.
*/
export type CommandPresentation = {
/**
* True under the fullscreen (alternate-screen) layout; false on the main
* screen (`CLAUDE_CODE_NO_FLICKER=0`, tmux by default) and headless.
*/
isFullscreen: boolean;
/**
* The terminal's width in cells as the command runs; 80 where no terminal
* has measured (headless with no tty).
*/
columns: number;
};
/**
* `command.run`'s input as a plugin's `$.command.run` takes it: `args` may
* be left out (`/command`, bare); `origin` and `presentation` the engine sets.
*/
export type CommandRunArgs = Omit<CommandRunInput, 'origin' | 'args' | 'presentation'> & {
/**
* Everything after the name, as the person would type it; left out, `""`.
*/
args?: string;
};
/**
* The input of `command.run`: one slash command about to run, the way the
* person typed it (`/name args`), and where the run came from.
*/
export type CommandRunInput = {
/**
* Names the command without its slash (`compact`, `hello`), aliases and
* folds resolved; the key a matcher narrows on. A rewrite is refused.
*/
command: string;
/**
* Everything after the name, as typed (`""` when nothing was); a hook
* rewrites it with `next({ ...e, args })`.
*/
args: string;
/**
* Where the run came from, in `prompt.submit`'s words (PromptOrigin):
* the person's Enter (`composer`), the bridge, the SDK, or a plugin.
*
* A plugin's `$.command.run` reads `{ kind: 'plugin', name }`. `next(e)`
* passes it on as received.
*/
origin: PromptOrigin;
/**
* Where the command's answer will show (CommandPresentation): the
* fullscreen layout or the main screen, and the terminal's width.
*
* Pinned: the engine stamps it, `next(e)` passes it on, a rewrite that
* leaves it out keeps it and one that changes it is refused.
*/
presentation: CommandPresentation;
};
/**
* What a `command.run` hook returns and what `next(e)` and `$.command.run`
* resolve to: the command's output text, when it has one.
*
* From core, `text` is what the command printed (a `local` command's
* returned text; a panel command may print nothing) and `ref` names the
* run. A hook's own answer without `next` runs no command: its `text` is
* shown as the command's output, under the names of the plugins hooking
* the command unless each is bundled with Claude Code, whose answer reads
* as the built-in command's own.
*/
export type CommandRunResult = {
/**
* The command's output as a transcript line, or undefined when the
* command showed nothing as text (a panel, a prompt for the model).
*/
text?: string;
/**
* Set by core on what `next(e)` resolves to: names the engine's run of
* the command (its result stays on the host side).
*
* A hook that returns the object it got makes the engine use that run
* verbatim. Absent on a hook's own `{ text }` and on `$.command.run`'s.
*/
ref?: number;
};
/**
* Where a slash command comes from, as `$.command.list()` tells them apart.
*
* `builtin` ships with Claude Code; `plugin` is a plugin's markdown command,
* skill or `$.command.register`; `user` is the user's or project's own
* file; `mcp` an MCP server's prompt.
*/
export type CommandSource = 'builtin' | 'plugin' | 'user' | 'mcp';
/**
* What `$.command.register` takes: the slash command this plugin serves.
*/
export type CommandSpec = {
/**
* The command's name without the slash (letters, digits, `_`, `-`; up to
* 64); the person runs it as `/<name>`.
*/
name: string;
/**
* The one line the typeahead and `/help` show for it.
*/
description: string;
/**
* The hint drawn dim after the name (`[name]`), when it takes arguments.
*/
argumentHint?: string;
/**
* Set so that `/<name>` typed while a turn is in flight runs at once
* instead of waiting for the turn to end, as it does when left out.
*
* Its `command.run` hook then runs while a turn may still be streaming and
* must not assume the turn's state (what the transcript holds, whether a
* tool is mid-call); its `{ text }` prints as an idle run's does.
*/
immediate?: true;
};
type ConfigChangeHookInput = BaseHookInput & {
hook_event_name: 'ConfigChange';
source: 'user_settings' | 'project_settings' | 'local_settings' | 'policy_settings' | 'skills';
file_path?: string;
};
/**
* The input of `config.describe`: how one `/config` row presents, at the
* moment the menu lists it (and for `$.config.list`).
*/
export type ConfigDescribeInput = {
/**
* Names the row, as `config.set`'s `key` does; the key a matcher narrows
* on. Pinned: a rewrite is refused.
*/
key: string;
/**
* What the menu draws for the row, before its value.
*/
label: string;
/**
* The help text beneath the label, when the row has one (a plugin
* field's `description`); absent for the panel's own rows.
*/
description?: string;
/**
* Whether the menu leaves the row out; a hidden row still answers
* `$.config.set` and `/config key=value`.
*/
isHidden: boolean;
/**
* Who owns the row, as `config.set`'s `provider`. Pinned.
*/
provider: Origin;
};
/**
* What a `config.describe` hook returns: the label, help text and hidden
* flag the menu uses; the key and provider stay as they were.
*/
export type ConfigDescribeResult = Omit<ConfigDescribeInput, 'key' | 'provider'>;
/**
* How a `/config` row takes its value: `boolean` toggles, `choice` picks one
* of its `options`, `text` takes a string, `number` a number.
*/
export type ConfigKind = 'boolean' | 'choice' | 'text' | 'number';
/**
* Where a `config.set` came from, in `prompt.submit`'s words: the person
* in the `/config` menu (`composer`), the bridge, or a plugin, named.
*
* Set by the engine; `next(e)` passes it on as received and none sets it.
*/
export type ConfigOrigin = {
/**
* The person's own change in the `/config` menu (a toggle, a pick, a
* typed value), or their `/config key=value`.
*/
kind: 'composer';
} | {
/**
* A `/config key=value` that arrived over the Remote Control bridge (a
* phone or web client, or a relay): not attestably the owner's hand.
*/
kind: 'bridge';
} | {
/**
* A plugin's `$.config.set`; that plugin's own hooks do not see it.
*/
kind: 'plugin';
/**
* The calling plugin's name.
*/
name: string;
};
/**
* One `/config` row as `$.config.list()` returns it: what the menu would
* draw now, after every `config.describe` hook, a hidden row left out.
*/
export type ConfigRow = {
/**
* Names the row: the panel's id for a built-in, `<plugin>.<field>` for a
* plugin's `userConfig` field; what `$.config.set` takes.
*/
key: string;
/**
* What the menu draws for the row, before its value.
*/
label: string;
/**
* The help text under the label, when the row has one.
*/
description?: string;
/**
* How the row takes its value (ConfigKind).
*/
kind: ConfigKind;
/**
* What the row holds now.
*/
value: ConfigValue;
/**
* The values a `choice` row takes, in order (a plugin string field's
* declared `options` for its row); absent otherwise.
*/
options?: readonly string[];
/**
* Who owns the row: the engine for the panel's own, else the plugin.
*/
provider: Origin;
/**
* Whether a trusted source (managed settings, the organization's policy)
* owns the value, so the menu shows it and refuses a change.
*/
isLocked: boolean;
};
/**
* `config.set`'s input as a plugin's `$.config.set(args)` takes it: the
* row's key and the value; the engine fills the rest.
*/
export type ConfigSetArgs = Pick<ConfigSetInput, 'key' | 'value'>;
/**
* The input of `config.set`: one `/config` row about to change, from the
* menu or a plugin's `$.config.set`, with what it holds now and who owns it.
*/
export type ConfigSetInput = {
/**
* Names the row: the panel's own id for a built-in (`theme`, `verbose`,
* `autoCompact`), `<plugin>.<field>` for a plugin's `userConfig` field.
*
* The key a matcher narrows on; pinned: a rewrite is refused.
*/
key: string;
/**
* What the row is being set to; `next({ ...e, value })` clamps or
* replaces it, held to the row's kind (a toggle takes a boolean).
*/
value: ConfigValue;
/**
* What the row holds before the change, as the menu shows it. Pinned.
*/
previous: ConfigValue;
/**
* Who owns the row: `{ plugin: "engine", tier: "core" }` for the panel's
* own, the plugin and its tier for a `userConfig` field. Pinned.
*/
provider: Origin;
/**
* Where the change came from (ConfigOrigin): the person in the menu
* (`composer`) or a plugin's `$.config.set`. Pinned.
*/
origin: ConfigOrigin;
};
/**
* What a `config.set` hook returns and what `next(e)` resolves to:
* `{ value }` once written, or `{ deny: reason }`, the row left as it was.
*
* The menu shows a deny's reason beside the row; a plugin's `$.config.set`
* resolves with it.
*/
export type ConfigSetResult = {
value: ConfigValue;
deny?: undefined;
} | {
deny: string;
value?: undefined;
};
/**
* A `/config` row's value as a hook and `$.config` see it: a toggle's
* boolean, a choice's or a text's string, a number, or a list of strings.
*/
export type ConfigValue = boolean | string | number | readonly string[];
/**
* One custom agent whose description the Agent tool's prompt carries;
* built-in agents are left out.
*/
export type ContextAgent = {
/**
* The agent's type, as the Agent tool names it.
*/
agentType: string;
/**
* Where it was defined, by the engine's word (`projectSettings`,
* `userSettings`, `plugin`); the display label is the renderer's.
*/
source: string;
/**
* The description's estimated tokens.
*/
tokens: number;
};
/**
* The token counts the last API response of the live window reported, as
* the API spells them; the breakdown's `Messages` row is reconciled to it.
*/
export type ContextApiUsage = {
/**
* Uncached input tokens the response was answered over.
*/
input_tokens: number;
/**
* Tokens the response generated.
*/
output_tokens: number;
/**
* Input tokens written to the prompt cache by the request.
*/
cache_creation_input_tokens: number;
/**
* Input tokens read from the prompt cache by the request.
*/
cache_read_input_tokens: number;
};
/**
* How a context breakdown is counted: `full` with the token-count API per
* category, `summary` from the last response's usage and local estimates.
*
* The SDK's `get_context_usage` takes the same two words as its `detail`.
*/
export type ContextBreakdownDetail = 'summary' | 'full';
/**
* One row of the breakdown, as /context lists it beside the grid (`System
* prompt`, `Messages`, `Free space`, `Autocompact buffer`).
*/
export type ContextCategory = {
/**
* The row's label as /context prints it.
*/
name: string;
/**
* The row's estimated tokens; a `deferred` row's do not count toward the
* total.
*/
tokens: number;
/**
* The theme colour /context draws the row and its squares in, by its key
* in the theme (`promptBorder`, `inactive`, `permission`).
*/
color: string;
/**
* Whether the row is tool schemas loaded on demand, which the grid leaves
* out; the same fact as `kind` `deferred`.
*/
isDeferred: boolean;
/**
* What the row is (ContextCategoryKind), stamped by the engine.
*/
kind: ContextCategoryKind;
};
/**
* What a breakdown row is; branch on this, never on the row's `name`.
*
* `used` content occupies the window, `free` is the window left, `buffer`
* the compaction reserve, `deferred` tool schemas loaded on demand and
* outside the window.
*/
export type ContextCategoryKind = 'used' | 'free' | 'buffer' | 'deferred';
/**
* One square of the grid /context draws: which row it belongs to and how
* full it is.
*/
export type ContextGridSquare = {
/**
* The theme colour of the square's row, by its key in the theme.
*/
color: string;
/**
* Whether the square holds any of its row's tokens.
*/
isFilled: boolean;
/**
* The `name` of the row the square belongs to (`Free space` for the
* window left).
*/
categoryName: string;
/**
* The row's tokens, repeated on each of its squares.
*/
tokens: number;
/**
* The row's share of the window as a whole percentage, repeated likewise.
*/
percentage: number;
/**
* How full this one square is, 0 to 1: a row's last square is the partial
* one (/context draws it hollow under 0.7).
*/
squareFullness: number;
};
/**
* One MCP tool's schema as the context carries it.
*/
export type ContextMcpTool = {
/**
* The tool's wire name (`mcp__linear__create_issue`).
*/
name: string;
/**
* The server it belongs to, as /mcp lists it.
*/
serverName: string;
/**
* The schema's estimated tokens.
*/
tokens: number;
/**
* Whether the schema is inside the window now: always, unless tool
* schemas load on demand and this one has not been searched for yet.
*/
isLoaded: boolean;
};
/**
* One memory file the context carries (a CLAUDE.md, a rules file, an
* auto-memory entry).
*/
export type ContextMemoryFile = {
/**
* The file's path, absolute.
*/
path: string;
/**
* The display label of where it was loaded from (`Project`, `User`,
* `Local`, `Managed`, `AutoMem`).
*/
type: string;
/**
* The file's estimated tokens.
*/
tokens: number;
};
/**
* One skill whose listing the context carries.
*/
export type ContextSkill = {
/**
* The skill's name as `/skills` lists it.
*/
name: string;
/**
* Where it came from, by the engine's word (`userSettings`, `plugin`,
* `built-in`, `mcp`, `syncedSkills`); the display label is the renderer's.
*/
source: string;
/**
* The providing plugin's name, when the skill comes from one.
*/
pluginName?: string;
/**
* The listing's estimated tokens.
*/
tokens: number;
};
/**
* The skills the context lists for the model: how many there are, how many
* fit the listing's budget, and each one's share.
*/
export type ContextSkills = {
/**
* How many skills the session has.
*/
totalSkills: number;
/**
* How many the listing included within its token budget.
*/
includedSkills: number;
/**
* The listing's tokens in all.
*/
tokens: number;
/**
* One entry per listed skill.
*/
skillFrontmatter: ContextSkill[];
};
/**
* The slash commands the Skill tool's prompt lists, counted.
*/
export type ContextSlashCommands = {
/**
* How many commands the session has.
*/
totalCommands: number;
/**
* How many the listing included.
*/
includedCommands: number;
/**
* The listing's tokens in all.
*/
tokens: number;
};
/**
* How the window the breakdown measures against was settled; /context
* prints its `Auto-compact window` line off this.
*
* `auto` is the model's own limit; the rest name a compaction window by who
* set it: the `CLAUDE_CODE_AUTO_COMPACT_WINDOW` variable, the settings, the
* account, an experiment, the model's default, or an unrecognised model's.
*/
export type ContextWindowSource = 'env' | 'settings' | 'clientdata' | 'experiment' | 'model-default' | 'unknown-model' | 'auto';
/**
* The plugin's identity (`plugin`) and the nouns core contributes to `$` as
* the innermost step of the `engine.create` fold.
*
* A plugin's finished `$` (EngineInterface) has every core noun an outer
* step did not withhold, and every noun the plugins' steps added.
*/
export interface CoreEngineInterface {
/**
* This plugin, as loaded: its manifest name and its directory.
*/
plugin: {
/**
* From plugin.json; debug-log and `$.ui.log` lines carry it.
*/
name: string;
/**
* The plugin's directory (the one holding plugin.json), absolute.
*/
root: string;
};
/**
* Display: a line under an open dialog, a redraw or a repaint, a
* transcript line, a pane the surface places, a window or a ring moved.
*/
ui: {
/**
* Shows `text` as one line under the dialog open for `tool_use_id`, or
* removes the line when `text` is undefined.
*
* Core removes the line when the call resolves. A call that is not open
* is refused, as is another plugin's `$.tool.call` run.
*
* @param tool_use_id the call whose open dialog gets the line
* @param text the line to show; undefined removes it
* @example
* $.ui.notice(e.tool_use_id, "checked by my-plugin"); return next(e)
*/
notice: (tool_use_id: string, text: string | undefined) => void;
/**
* Re-runs an event whose results the engine caches: `ui.render` draws the
* instances this plugin may draw again; the others drop the cached answers.
*
* A render hook whose state changed (a countdown) calls it for a redraw, at
* most ten a second, thirty for the shown pane and the band (calls sooner
* fold); a `prompt.section` or `prompt.context` hook: dropped next turn.
*
* @param event `ui.render`, `prompt.section`, `prompt.context`,
* `tool.describe`, `command.describe` or `config.describe`
*/
invalidate: (event: InvalidatableEventName) => void;
/**
* Repaints a `Raster` this plugin's own render hook drew, still mounted,
* with new cells, without the redraw `invalidate` asks for.
*
* The surface keeps the cells for that Raster (by site and `key`) and
* paints them at its next frame, so blits between frames fold into one:
* an animation runs at the frame rate. A resize is a redraw instead.
*
* @param args `requestId` (the site), `key` (the Raster's), `cells`
* (RasterProps), `columns` and `rows` (the mounted size)
* @returns `{}` once the cells are its next frame, or `{ deny }` (not
* mounted, not this plugin's, another size, cells that do not
* decode)
* @example
* $.clock.every(33, () => $.ui.blit({ requestId, key, cells: frame() }))
*/
blit: (args: UiBlitArgs) => Promise<UiBlitResult>;
/**
* The elements of the surface `e` is drawn on (Elements[e.surface]): a
* frozen table of constructors, the JSX tags a render hook draws with.
*
* A read, not a dispatch: the engine ran `ui.resolve` (the other hooks,
* then core) at load, per surface and component. Narrowed `e.surface`:
* that table exactly; unnarrowed: the union, so shared names type-check.
*
* @param e this hook's own `ui.render` argument (its surface and
* component pick the table)
* @returns the surface's frozen element table (`Elements[e.surface]`)
* @example
* const { Box, Text } = $.ui.resolve(e)
* return <Box>{await next(e)}<Text dimColor>done</Text></Box>
*/
resolve: <E extends ResolveInput>(e: E) => Elements[E['surface']];
/**
* Appends one line to the transcript, drawn like a system notice (dim;
* not sent to the model), and records it in the debug log.
*
* The line is a row of its own at the surface's next frame, wherever the
* transcript is then; lines keep the order they were logged in. A `-p` or
* SDK run has no transcript: its host receives the line as `ui_log`.
*
* @param text the line's text
* @example
* $.ui.log(`prompt from ${e.origin.kind}: ${e.text.length} chars`)
*/
log: (text: string) => void;
/**
* Asks the user `question` in the engine's own AskUserQuestion dialog and
* resolves to the label they chose, or the text typed under "Other".
*
* A `tool.call` of `AskUserQuestion` through every hook but the calling
* one, drawn by `ui.render` on `AskUserQuestion`; a multi-select answer is
* comma-joined. Rejects when dismissed, and in a `-p` run (no one to ask).
*
* @param question the question, ending in a question mark
* @param options 2-4 option labels, or `{ options, header, multiSelect }`
* @returns the label chosen, the chosen labels comma-joined, or free text
* typed under "Other" (so compare it with the labels exactly)
* @example
* const mood = await $.ui.ask("How careful?", ["Bold", "Careful"])
*/
ask: (question: string, options?: readonly string[] | AskOptions) => Promise<string>;
/**
* Shows `text` on the notification bar under the prompt for a few
* seconds, the way the engine's own "context left" notice appears.
*
* It leaves the transcript and the model untouched.
*
* @param text the line to show
* @param options `timeoutMs`: how long it stays (default 4000)
* @example
* $.ui.toast(`turn took ${Math.round(e.durationMs / 1000)} s`)
*/
toast: (text: string, options?: ToastOptions) => void;
/**
* Pins `text` as this plugin's status line under the prompt, beside the
* engine's own pinned notices, until the next call replaces it.
*
* One per plugin; `undefined` removes it.
*
* @param text the line to keep on screen; undefined clears it
* @example
* $.ui.status("thinking..."); return next(e)
*/
status: (text: string | undefined) => void;
/**
* Opens a pane: a framed region the surface places, whose body this
* plugin draws by hooking `ui.render` for `{ component: "Pane" }`.
*
* One instance per id (`requestId`): opening an open id retitles it; a hook
* on `ui.open` may refuse it. The keyboard is the person's; unasked, it
* waits undrawn below 144 columns (110 once asked), judged at each open.
*
* @param pane `id` (1-64 of letters, digits, `_`, `-`), `title`, `focus`,
* `closeOnEscape` and `holdToasts` (a dialog), `rows` it wants inline
* @returns settles once the pane is open (or retitled)
* @example
* await $.ui.open({ id: "clock", title: "Clock" })
* @example
* await $.ui.open({ id: "ask", focus: true, closeOnEscape: true, rows: 9 })
*/
open: (pane: PaneOpenArgs) => Promise<void>;
/**
* Closes one of the open panes; an id that is not open is left alone.
*
* Every close raises `ui.close`, `e.origin` naming whose it is: this call
* (`plugin`), the person's mark or key (`person`), an unload (`unload`).
* A hook answering without `next` keeps the pane open, save on an unload.
*
* @param pane `id`: the id the pane was opened under
* @returns settles once the pane is gone or a hook answered for it;
* rejects on a hook's `{ deny }`
* @example
* onPress: () => $.ui.close({ id: "clock" })
*/
close: (pane: PaneCloseArgs) => Promise<void>;
/**
* Scrolls something into view as the DOM's `scrollIntoView` would: a
* render instance by `requestId`, an element by `key`, a site's edge.
*
* A site of this plugin's (its pane, the band it draws into) moves under
* the event `ui.scroll`, origin `plugin`. A transcript row moves only
* while this call answers the person's own input, where one scrolls.
*
* @param args `to` (what), `in` (which site, required for `start` and
* `end`), `block` (where it lands; `nearest` by default)
* @returns `{}` once it moved, or `{ deny }` saying why not
* @example
* onPress: () => $.ui.scroll({ in: "log", to: "end" })
*/
scroll: (args: UiScrollArgs) => Promise<UiScrollResult>;
/**
* Moves the focus ring of one of this plugin's sites onto an element it
* drew there, as the DOM's `element.focus()`, while it holds the keys.
*
* Raised as the event `ui.focus`, origin `plugin`; the engine's inverse
* marks the element. The keyboard is the person's to give: a site not
* holding it, or holding it on another plugin's element, is `{ deny }`.
*
* @param args `requestId` (which site: a pane's id, the band's) and `key`
* (the element's, as drawn)
* @returns `{}` once it moved, or `{ deny }` saying why not
* @example
* onPress: () => $.ui.focus({ requestId: "files", key: "row:0" })
*/
focus: (args: UiFocusArgs) => Promise<UiFocusResult>;
};
/**
* Completions through the session's own client and credentials.
*/
model: {
/**
* Runs one text completion through the session's own API client and
* resolves to the reply's text.
*
* No tools, no history, no system prompt beyond the CLI's identity block
* and `request.system`.
*
* @param request the model (an alias such as `haiku`, or a full id,
* resolved like a `--model` value), the prompt, and a token cap
* @returns the reply's text
* @example
* const reply = await $.model.complete({ model: "haiku", prompt: "Hi." })
*/
complete: (request: ModelCompleteRequest) => Promise<string>;
/**
* Runs one tool-less completion over the session's OWN transcript, sharing
* the main thread's prompt cache; the reply's text and the fork's usage.
*
* Not `complete`: sharing the cache prefix means the model and system
* prompt are the session's, read from its last turn's cache-safe snapshot,
* and tools are denied. Null on a cold snapshot or an API error.
*
* @param request the one user message the fork answers
* @returns the reply's text with the fork's usage, or null on a cold
* snapshot or an API error
* @example
* const reply = await $.model.fork({ prompt: "One line to learn?" })
* if (reply !== null) $.ui.log(`${reply.usage.output_tokens} tokens`)
*/
fork: (request: ModelForkRequest) => Promise<ModelForkResult | null>;
/**
* Picks one of `labels` for `text` with one completion over
* `$.model.complete` and a fixed classifier prompt.
*
* `text` is data; the model answers with a label alone. It resolves
* `undefined` when the answer named none of `labels`. A failed request,
* an abort or a reply with no text rejects, naming the cause.
*
* @param text what to classify
* @param labels the labels to choose from (2 or more)
* @param options `model`: an alias or id; default the engine's small
* fast model
* @returns the label the model named, or undefined when it named none;
* rejects when the request fails or the reply has no text
* @example
* const kind = await $.model.classify(e.text, ["bug", "feature"])
* if (kind === undefined) return next(e)
*/
classify: (text: string, labels: readonly string[], options?: ClassifyOptions) => Promise<string | undefined>;
};
/**
* Sound: clip playback and platform speech.
*/
audio: {
/**
* Plays one audio clip, starting now; clips are not queued, so two calls
* play together (a bed under speech).
*
* `{ asset }` is the plugin's own file, loaded by the engine and played
* through the platform's player (`afplay` on macOS). Resolves when
* playback ends; rejects, naming the cause, when the clip cannot play.
*
* @param clip the plugin's own file (`{ asset }`), a URL the engine
* fetches, or the bytes as base64 with their MIME type
* @param options `shouldLoop`, `gain`, and an AbortSignal that stops the
* clip
*/
play: (clip: AudioClip, options?: PlayOptions) => Promise<void>;
/**
* Speaks `text` with the platform's own synthesizer (`say` on macOS).
* Plain text.
*
* Utterances are queued among themselves; clips are not. Resolves when
* the utterance has ended; rejects, naming the cause, when there is no
* synthesizer, the voice is not installed, or the utterance failed.
*
* @param text what to say, as plain text
* @param options `voice`: the system voice's exact name (`Samantha`);
* absent, the synthesizer's default
* @returns which synthesizer spoke, once the utterance has ended
*/
speak: (text: string, options?: SpeakOptions) => Promise<SpeakResult>;
};
/**
* The engine's connected MCP servers.
*/
mcp: {
/**
* Calls `tool` on one of the engine's connected MCP servers with the
* engine's own connection and credentials.
*
* A `cached` server is dialed on first use. Resolves to the tool's result
* as MCP returns it: `content` blocks and `isError`. No permission prompt:
* the plugin's call, seen by the hooks above it, is the grant.
*
* @param server the server's name as /mcp lists it (`claude.ai Gmail`;
* the tool-name spelling `claude_ai_Gmail` is accepted too)
* @param tool the tool's name on that server (`create_draft`)
* @param args the tool's arguments; none when absent
* @returns the tool's result as MCP returns it: `content` blocks and
* `isError`
* @example
* const { content } = await $.mcp.call("claude.ai Gmail", "create_draft")
*/
call: (server: string, tool: string, args?: Record<string, unknown>) => Promise<McpToolResult>;
};
/**
* The running session, read as plain data, and compacting it.
*/
session: {
/**
* Returns the transcript so far, one entry per user or assistant
* message; progress rows, `$.ui.log` lines and notices are not messages.
*
* Each entry is a SessionMessage, `{ role, text, toolUses }` (a user
* message may add `toolResults`; a `toolUses` entry adds its `result` and
* `text` once answered). A long transcript answers its newest 4096.
*
* @example
* const last = (await $.session.messages()).at(-1)
*/
messages: () => Promise<SessionMessage[]>;
/**
* Returns the directory the session runs in, absolute.
*/
cwd: () => Promise<string>;
/**
* Returns the main loop's model, as `/model` shows it.
*/
model: () => Promise<string>;
/**
* Returns how many prompts the user has sent this session (user turns in
* the transcript).
*/
turns: () => Promise<number>;
/**
* Returns the session's id (the transcript file's name).
*/
id: () => Promise<string>;
/**
* Returns the git repository the session runs in, read from the working
* copy on each call; null when the directory is not inside one.
*
* @example
* const repo = await $.session.repo(); const publicRepo = !repo?.internal
*/
repo: () => Promise<SessionRepo | null>;
/**
* Returns every surface the session draws on, each once: `terminal` under
* the REPL first, then the remote ones in the order they attached.
*
* A session may draw on several at once (a terminal and two phones):
* clients attach (`session.attach`) and detach, and a render hook still
* reads `e.surface` per ask. Empty in a plain -p run; never rejects.
*
* @example
* const inApp = (await $.session.surfaces()).some(s => s !== "terminal")
*/
surfaces: () => Promise<readonly RenderSurface[]>;
/**
* Returns the first of `$.session.surfaces()`, or null where nothing
* draws.
*
* @deprecated use `surfaces()`; a session may draw on several surfaces at
* once
*/
surface: () => Promise<RenderSurface | null>;
/**
* Returns the context window's fill, the rate-limit windows and the
* cost, as the status line has them; with `breakdown`, by category too.
*
* The plain call costs nothing; `"full"` counts each category with the
* token-count API as /context does, `"summary"` estimates locally, and
* `context.breakdown` comes back in the SDK's `get_context_usage` shape.
*
* @param args `{ breakdown, columns }`: how the breakdown is counted and
* the width its grid is drawn in; nothing for the status line's figures
* @returns `{ context, rateLimits, cost }` as the status line has them
* @example
* const { context } = await $.session.usage()
* if ((context.percent ?? 0) >= 85) await $.session.compact()
* @example
* const usage = await $.session.usage({ breakdown: "full", columns })
* for (const row of usage.context.breakdown?.gridRows ?? []) draw(row)
*/
usage: (args?: SessionUsageArgs) => Promise<SessionUsage>;
/**
* Compacts the conversation: the event `session.compact` with `trigger`
* `plugin`, the same call `/compact` makes, between turns.
*
* It runs through every hook but the calling one, then core: a summary
* and the kept messages in the transcript's place. Resolves `{ skip }`
* when a hook vetoed it; rejects while a turn runs.
*
* @example
* const { skip } = await $.session.compact({ instructions: "the plan" })
*/
compact: EventCalls['session']['compact'];
/**
* Holds the session's Anthropic credential on the host and answers an
* opaque handle and its kind; the secret never reaches the plugin.
*
* The handle is spent through `$.http.fetch(url, { auth: handle })`,
* which sets the credential header, only for a first-party host. Null
* where the build or the provider has no first-party credential to hold.
*
* @example
* await $.http.fetch(url, { auth: (await $.session.authorize())?.handle })
*/
authorize: () => Promise<SessionAuthorization>;
};
/**
* The running model turn: ending it.
*/
turn: {
/**
* Cancels the running model turn: the one whose id `turn.start` handed
* this plugin, its running tools stopped, no interruption marker.
*
* The event `turn.abort`, seen by the hooks above; the prompt this
* plugin submits next is the context. Rejects, naming both ids, when
* `turnId` is not the running turn's; a hook may end its own turn.
*
* @param input `turnId`: the id `turn.start` carried
* @example
* on("turn.start", ($, e, next) => { held = e.turnId; return next(e) })
*/
abort: (input: OpEventOf['turn.abort']) => Promise<void>;
};
/**
* Submitting a prompt the model reads as a user turn, and putting a text
* in the person's prompt box, written or proposed.
*/
prompt: {
/**
* Submits a prompt: the event `prompt.submit`, the same call the engine
* makes for a typed prompt; `input.text` runs when the session is idle.
*
* It goes through every hook but the calling one (the plugin's others
* see it) with `e.origin` `{ kind: 'plugin', name }`, the name the
* model reads it under unless a hook leaves it out of its answer.
*
* @example
* void $.prompt.submit({ text: "List the TODOs you just mentioned." })
*/
submit: EventCalls['prompt']['submit'];
/**
* Writes `input.text` into the prompt box as the person's draft, cursor
* at its end, replacing what it held: the event `prompt.fill`.
*
* It goes through every other plugin's hook with `e.origin` `{ kind:
* 'plugin', name }`. Resolves `{ isFilled: false }` when a dialog holds
* the keys or the session has no box (headless); nothing is submitted.
*
* @example
* const { isFilled } = await $.prompt.fill({ text: "/review latest" })
*/
fill: EventCalls['prompt']['fill'];
/**
* Proposes `input.text` as the prompt box's dim suggestion, Tab to take:
* the event `prompt.suggest`, as the engine's own guess after a turn.
*
* It goes through every other plugin's hook with `e.origin` `{ kind:
* 'plugin', name }`, the engine's own suggestions on or off; `{ isShown:
* false }` while the box holds text, a turn runs, or headless (no box).
*
* @example
* void $.prompt.suggest({ text: "run the tests you just wrote" })
*/
suggest: EventCalls['prompt']['suggest'];
};
/**
* The tools the model has in this session, and running one.
*/
tool: {
/**
* Returns the tools the model can call now, built-in and MCP alike, in
* the order the model sees them.
*
* @example
* const names = (await $.tool.list()).map(t => t.name)
*/
list: () => Promise<ToolInfo[]>;
/**
* Calls a tool: the event `tool.call`, the same call the engine makes for
* the model's tool calls, under a `tool_use_id` of its own.
*
* It runs through every hook but the calling one (the plugin's others
* see it), the permission check and its dialog, then the tool. Rejects
* when no tool has that name or the call is aborted.
*
* @example
* const { text } = await $.tool.call({ tool: "Read", file_path: "a.md" })
*/
call: EventCalls['tool']['call'];
/**
* Asks the engine's permission decision for a tool call now: the event
* `tool.check`, resolved to `{ decision, reason?, rule? }`.
*
* The hooks run (the calling hook's own frame skipped, `next.origin` this
* plugin, no `tool_use_id`); nothing runs, no dialog opens, no PreToolUse
* hook or classifier is asked.
*
* @example
* const { decision } = await $.tool.check({ tool: "Read", input })
*/
check: EventCalls['tool']['check'];
/**
* Declares a tool the model can call from the next prompt on: the name,
* description and input schema of `mcp__<plugin>__<name>`.
*
* Serve it with a `tool.call` hook on `{ tool: "mcp__<plugin>__<name>" }`
* that returns the result (a call no hook answers fails); a name registered
* again is replaced. Rejects until the session binds, at `session.start`.
*
* @param tool `name`, `description` (what the model reads), `inputSchema`
* (a JSON schema object; default `{ type: "object" }`)
* @returns `{ tool }`, the registered tool's full name
* `mcp__<plugin>__<name>`
* @example
* await $.tool.register({ name: "weather", description: "Weather." })
*/
register: (tool: ToolSpec) => Promise<OpValueOf['tool.register']>;
};
/**
* The slash commands the person can run in this session, and running one.
*/
command: {
/**
* Returns the slash commands the person can run now, built-in, plugin
* and MCP alike, in the order the typeahead lists them.
*
* @example
* const names = (await $.command.list()).map(c => c.name)
*/
list: () => Promise<CommandInfo[]>;
/**
* Runs a slash command as if the person typed `/command args`: the
* event `command.run`, queued and run once the session is idle.
*
* It runs through every hook but the calling one with `e.origin`
* `{ kind: 'plugin', name }`, its lines in the transcript. Rejects an
* unknown name, and inside a hook the turn is waiting on.
*
* @example
* const { text } = await $.command.run({ command: "status" })
*/
run: EventCalls['command']['run'];
/**
* Declares the slash command `/<name>` for this session, listed in the
* typeahead from the next keystroke on.
*
* Serve it with a `command.run` hook on `{ command: "<name>" }` that
* returns `{ text }`; a run no hook answers says so as its output.
* Registering a name again replaces it; a built-in's name is refused.
*
* @param command `name`, `description` (what the menu shows),
* `argumentHint` (dim after the name), `immediate` (runs mid-turn)
* @returns `{ command }`, the registered name
* @example
* await $.command.register({ name: "hello", description: "Says hi." })
*/
register: (command: CommandSpec) => Promise<OpValueOf['command.register']>;
};
/**
* Every row of the settings menu (`/config`), the panel's own and each
* enabled plugin's `userConfig` fields alike: listing and changing them.
*/
config: {
/**
* Returns the rows the `/config` menu would draw now, in its order,
* each with its current value, its kind, its owner and its lock.
*
* After every `config.describe` hook: a hidden row is left out, a
* relabelled one carries the new label.
*
* @example
* const theme = (await $.config.list()).find(row => row.key === "theme")
*/
list: () => Promise<ConfigRow[]>;
/**
* Changes one row as if the person did in the menu: the event
* `config.set` with `origin` `{ kind: 'plugin', name }`, then the writer.
*
* Through the other plugins' hooks, this plugin's own skipped; `{ deny }`
* when a hook refused, the value does not fit, a trusted source owns the
* row or only its dialog changes it. Rejects a key no row has.
*
* @param args `key` (as `list` names it) and `value` (the row's kind)
* @returns `{ value }` once written, or `{ deny }`
* @example
* const { deny } = await $.config.set({ key: "verbose", value: true })
*/
set: EventCalls['config']['set'];
};
/**
* Subagents.
*/
agent: {
/**
* Spawns a subagent: the event `agent.spawn`, the same call the engine
* makes when the Agent tool starts one; the engine fills the rest.
*
* It runs every hook but the calling one, then the Agent tool in the
* background under this call's origin: `{ model, agentId }` once the
* subagent started (its answer is its `turn.complete`), or `{ deny }`.
*
* @example
* const { agentId } = await $.agent.spawn({ prompt: "Read README.md." })
*/
spawn: EventCalls['agent']['spawn'];
/**
* Returns the session's subagents so far, the ones the model spawned and
* the ones plugins did alike.
*/
list: () => Promise<AgentInfo[]>;
};
/**
* The file system as the engine's own process reaches it, text only
* (UTF-8); a relative path is under the session's working directory.
*
* An absolute path is used as given. A read or a write over 4 MiB
* rejects; what the operating system refuses rejects with its errno
* (`ENOENT`, `EACCES`). Where a path may go is an `fs.*` hook's to say.
*/
fs: {
/**
* Reads a file and returns its text. Rejects when missing.
*
* @param path relative to the working directory, or absolute
* @returns the file's text
* @example
* const readme = await $.fs.read("README.md")
*/
read: (path: string) => Promise<string>;
/**
* Writes `text` to a file, creating it and its directories as needed.
*
* @param path relative to the working directory, or absolute
* @param text the whole new content
*/
write: (path: string, text: string) => Promise<void>;
/**
* Lists a directory: `{ name, kind, size }` per entry, by name.
*
* @param path the directory's path; absent, the working directory
* @returns the entries, `{ name, kind, size }` each
*/
list: (path?: string) => Promise<FsEntry[]>;
/**
* Returns whether the path exists; never rejects.
*/
exists: (path: string) => Promise<boolean>;
/**
* Returns `{ kind, size, mtimeMs }` of the path. Rejects when missing.
*/
stat: (path: string) => Promise<FsStat>;
/**
* Reads the named instruction files in every directory above the
* session's original working directory, the way the engine reads CLAUDE.md.
*
* Root first, each `{ dir, name, content }` that exists, the content
* with its `@include`s after it; with `of`, on down to that file's
* directory, as the engine reads a nested CLAUDE.md when a file is read.
*
* @param request `names`, relative `.md` file names (no `..`) looked for
* in each directory; `of`, the file whose directory the walk goes down to
* @returns the files found, root first
* @example
* const found = await $.fs.ancestors({ names: ["AGENTS.md"] })
* const stack = await $.fs.ancestors({ names: ["AGENTS.md"], of: path })
*/
ancestors: (request: FsAncestorsRequest) => Promise<readonly FsAncestor[]>;
};
/**
* This plugin's own key-value store, kept between sessions and hot
* reloads; values are JSON data.
*
* A JSON file of the plugin's own under the user's Claude Code
* configuration directory.
*/
store: {
/**
* Returns the value under `key`, or `undefined` when unset.
*
* @example
* const count = Number((await $.store.get("count")) ?? 0) + 1
*/
get: (key: string) => Promise<unknown>;
/**
* Sets `key` to `value`, which must be JSON data.
*
* `get` reads back `JSON.parse(JSON.stringify(value))`: a Date is its ISO
* string, an `undefined` field is dropped, a Map or Set is `{}`. Rejects
* a function, a cycle, or a store over 4 MiB of JSON text in all.
*/
set: (key: string, value: unknown) => Promise<void>;
/**
* Removes `key` from the store.
*/
delete: (key: string) => Promise<void>;
/**
* Returns every key set, in insertion order.
*/
keys: () => Promise<string[]>;
};
/**
* The time and timers, each an event through the host: `clock.now` reads
* the time; `clock.sleep`, `after` and `every` wait until it has passed.
*
* A timer's callback is the plugin's own function, kept in its environment
* and run there when the wait resolves; a hot reload of the plugin cancels
* its pending waits with the old environment.
*/
clock: {
/**
* Resolves milliseconds since the epoch, now.
*
* @example
* const startedAt = await $.clock.now()
*/
now: () => Promise<number>;
/**
* Resolves after `ms` milliseconds; rejects at once when `signal` aborts.
*
* @param ms how long, in milliseconds
* @param options `signal`: ends the wait early with a rejection (pass
* `next.signal` so a hook's wait ends with its dispatch)
* @example
* await $.clock.sleep(500, { signal: next.signal })
*/
sleep: (ms: number, options?: SleepOptions) => Promise<void>;
/**
* Calls `fn` once after `ms` milliseconds; `cancel()` before then stops it.
*
* One `clock.after` dispatch: `fn` runs when it resolves, and never when
* a hook refuses it.
*/
after: TimerCall;
/**
* Calls `fn` every `ms` milliseconds (at least 1) until `cancel()`.
*
* One `clock.every` dispatch per period: `fn` runs when it resolves and
* the next period is asked; a refused period ends the interval.
*
* @example
* const tick = $.clock.every(1000, () => $.ui.status("polling"))
*/
every: TimerCall;
};
/**
* The network, through the host.
*/
http: {
/**
* Fetches `url` through the host (never the plugin's own network) and
* resolves `{ status, ok, headers, text }` once the body is read.
*
* http or https, to whatever the host process can reach, unless the
* administrator's policy switches refuse it; an `auth` handle from
* `$.session.authorize()` rides https only, to a first-party host.
*
* @param url the URL (http or https)
* @param init `{ method, headers, body, auth }` (body a string)
* @returns `{ status, ok, headers, text }` once the body is read
* @example
* const { ok, text } = await $.http.fetch("https://example.com/status")
*/
fetch: (url: string, init?: HttpInit) => Promise<HttpResponse>;
};
/**
* Commands on the host, run as the user the session runs as. CLI only.
*
* Local execution, not a network path: what a command of its own reaches
* is its own, as for the Bash tool and a settings `command` hook.
*/
process: {
/**
* Runs a command on the host by its argument vector (no shell) and
* resolves `{ exitCode, stdout, stderr }` once it exits, any exit code.
*
* One shot: the whole output is read, so a background process left
* writing holds the call until the timeout. Rejects when the command
* cannot start or is still running then. Git runs with repo hooks off.
*
* @param argv the command and its arguments, `argv[0]` the executable
* @param init `{ cwd, env, stdin, timeoutMs }` (cwd the session's by
* default; timeout 30 s by default, ten minutes at most)
* @returns `{ exitCode, stdout, stderr }` once the child exits
* @example
* const { exitCode, stdout } = await $.process.run(["git", "status"])
*/
run: (argv: readonly string[], init?: ProcessRunInit) => Promise<ProcessRunResult>;
};
/**
* What the settings files, `--settings` and managed policy hold, as the
* engine runs under it; read only.
*
* Every key crosses as the source holds it, `env` and the helper commands
* included: nothing is filtered. The OAuth session and the global config
* (~/.claude.json) are not settings and are never read.
*/
settings: {
/**
* Resolves with the settings merged over every source, as the engine
* reads them, or with one source's settings as loaded (`{ source }`).
*
* A snapshot in plain data each call; a source with no file answers
* `{}`. The sources (SettingsSource) rise in precedence from `user` to
* `policy`: the merge takes a key from the last source that has it.
*
* @param args `{ source }` to read one source; nothing for the merge
* @returns the settings object, keyed as a settings.json is
* @example
* const { permissions } = await $.settings.read()
* const policy = await $.settings.read({ source: "policy" })
*/
read: (args?: SettingsReadArgs) => Promise<Settings>;
};
/**
* The environment of this process, the one every Bash child, MCP server
* and `$.process.run` command started after inherits.
*
* `get` and `set` take the variable's name as a string literal, so what a
* module reads and writes is read off its source: `claude plugin validate`
* lists the names, and a name the module does not spell is refused.
*/
env: {
/**
* Resolves with the variable's value, or `undefined` when it is unset.
*
* `name` must be a string literal; `claude plugin validate` lists the
* names your module reads and writes.
*
* @example
* const home = await $.env.get("HOME")
*/
get: (name: string) => Promise<string | undefined>;
/**
* Sets the variable for this process and everything it starts after, or
* unsets it when `value` is `undefined`.
*
* `name` must be a string literal; `claude plugin validate` lists the
* names your module reads and writes.
*
* @example
* await $.env.set("GIT_PAGER", "cat")
*/
set: (name: string, value: string | undefined) => Promise<void>;
};
}
/**
* The name of an event the engine defines itself (a key of CoreEventOf);
* EventName adds the declared plugin nouns' events.
*/
type CoreEventName = keyof CoreEventOf;
/**
* The argument of each event the engine defines itself: its call sites'
* (EngineEventOf), the classic hooks' (ClassicEventOf), the calls on `$`.
*/
type CoreEventOf = EngineEventOf & ClassicEventOf & OpEventOf;
type CwdChangedHookInput = BaseHookInput & {
hook_event_name: 'CwdChanged';
old_cwd: string;
new_cwd: string;
};
type DirectoryAddedHookInput = BaseHookInput & {
hook_event_name: 'DirectoryAdded';
/**
* Absolute path of the directory that was added.
*/
directory: string;
/**
* How the directory was added: "slash_command" for /add-dir, "register_repo_root" for the SDK control_request.
*/
source: 'slash_command' | 'register_repo_root';
};
/**
* The `children` field every element constructor's props carry, appended
* beside its own props type: one child, or a list that may nest.
*
* JSX types a lone child as the child itself (`<Text dimColor>done</Text>`
* passes the string, `<Text>{count}</Text>` the number), and a mapped list
* beside a sibling as a nested list (`<Box>{rows.map(row)}<Text>ok</Text>`).
*/
export type ElementChildren = {
children?: RenderChildren;
};
/**
* An element as `$.ui.resolve(e)` hands it out: a constructor from props to
* the frozen plain-data element, `children` among the props as JSX passes.
*
* `const { Box } = $.ui.resolve(e)` then `<Box gap={1}>...</Box>` compiles to
* `h(Box, { gap: 1 }, ...children)`, and `h` calls a function tag with its
* props, so the table's constructors are the JSX tags.
*/
export type ElementConstructor<P> = (props: P & ElementChildren) => RenderElement;
/**
* Every element name of every surface: what a table handed out is completed to
* (an omitted one draws a fragment; see `ui.resolve`).
*/
export type ElementName = {
[P in RenderSurface]: keyof Elements[P];
}[RenderSurface];
/**
* The element constructors each surface draws, by `e.surface`: what
* `$.ui.resolve(e)` returns and a `ui.resolve` hook passes on; no globals.
*
* All carry `Box`, `Text`, `Button`, `Link`, `Code`; every remote surface
* `Svg`; all but mobile `Input` and `Select`; terminal and desktop `Client`;
* terminal `Raster`. Narrowed on `e.surface`, that table; else the union.
*/
export type Elements = {
terminal: {
Box: ElementConstructor<BoxProps>;
Text: ElementConstructor<TextProps>;
Button: ElementConstructor<ButtonProps>;
Input: ElementConstructor<InputProps>;
Select: ElementConstructor<SelectProps>;
Link: ElementConstructor<LinkProps>;
Code: ElementConstructor<CodeProps>;
Client: ElementConstructor<ClientProps>;
Raster: ElementConstructor<RasterProps>;
};
desktop: {
Box: ElementConstructor<BoxProps>;
Text: ElementConstructor<TextProps>;
Button: ElementConstructor<ButtonProps>;
Input: ElementConstructor<InputProps>;
Select: ElementConstructor<SelectProps>;
Svg: ElementConstructor<SvgProps>;
Link: ElementConstructor<LinkProps>;
Code: ElementConstructor<CodeProps>;
Client: ElementConstructor<ClientProps>;
};
/**
* No `Input` or `Select`: the control protocol carries presses (ui_press)
* but no ui_input or ui_select yet; not a limit of the device.
*
* The table grows when those messages exist.
*/
mobile: {
Box: ElementConstructor<BoxProps>;
Text: ElementConstructor<TextProps>;
Button: ElementConstructor<ButtonProps>;
Svg: ElementConstructor<SvgProps>;
Link: ElementConstructor<LinkProps>;
Code: ElementConstructor<CodeProps>;
};
/**
* The desktop's table without `Client`: a remote `Client`'s module, presses
* and posts (ui_client_module, ui_client_press, ui_message) name no surface.
*
* They are the desktop's alone today, not a limit of the editor's webview:
* the table gains `Client` when those asks name a surface.
*/
vscode: {
Box: ElementConstructor<BoxProps>;
Text: ElementConstructor<TextProps>;
Button: ElementConstructor<ButtonProps>;
Input: ElementConstructor<InputProps>;
Select: ElementConstructor<SelectProps>;
Svg: ElementConstructor<SvgProps>;
Link: ElementConstructor<LinkProps>;
Code: ElementConstructor<CodeProps>;
};
};
/**
* The table `ui.resolve` answers for an argument of surface `P`.
*/
export type ElementTable<P extends RenderSurface = RenderSurface> = Elements[P];
/**
* Hook input for the Elicitation event. Fired when an MCP server requests user input. Hooks can auto-respond (accept/decline) instead of showing the dialog.
*/
type ElicitationHookInput = BaseHookInput & {
hook_event_name: 'Elicitation';
mcp_server_name: string;
message: string;
mode?: 'form' | 'url';
url?: string;
elicitation_id?: string;
requested_schema?: Record<string, unknown>;
};
/**
* Hook input for the ElicitationResult event. Fired after the user responds to an MCP elicitation. Hooks can observe or override the response before it is sent to the server.
*/
type ElicitationResultHookInput = BaseHookInput & {
hook_event_name: 'ElicitationResult';
mcp_server_name: string;
elicitation_id?: string;
mode?: 'form' | 'url';
action: 'accept' | 'decline' | 'cancel';
content?: Record<string, unknown>;
};
/**
* The input of `engine.create`: the fold that builds `$`, once per load,
* core innermost.
*
* A hook is written in post-order: `const built = await next(e)` is `$` as
* built so far; `return { ...built, voice: { say } }` adds this plugin's noun.
* See EngineEventOf's `engine.create` for what a step may and may not do.
*/
export type EngineCreateInput = {
/**
* In list order, first is outermost (managed plugins first, so an org
* plugin's withholding wins).
*/
plugins: readonly string[];
};
/**
* What an `engine.create` hook returns: `$` as built so far with this
* plugin's nouns added, less any it withheld.
*
* Every declared noun is optional here. Between hooks it crosses the chain
* as interface descriptors; a hook sees objects (EngineInterfaceBuilt).
*/
export type EngineCreateResult = Partial<EngineInterface> & {
readonly [noun: string]: unknown;
};
/**
* The events the engine raises at its call sites, and `engine.create`; the
* classic settings hooks' events are ClassicEventOf.
*
* At every one, a hook that fails (throws, overruns its budget, answers a
* wrong shape) is skipped: the hooks beneath and core run in its place, or
* its last `next` result stands; the failure is reported, naming it.
*/
export type EngineEventOf = {
/**
* Fires when the engine is about to run a tool. `next(e)` runs the hooks
* beneath, then core (the permission prompt, the tool itself).
*
* Return `{ deny: reason }` to refuse or `{ result }` to answer yourself; a
* hook that returns while its `next` is pending aborts what runs beneath.
* The managed-settings hooks run first: their deny is the call's result.
*/
'tool.call': ToolCallInput;
/**
* Fires when the engine decides whether a tool call may run, after the
* `tool.call` and PreToolUse hooks and before the mode settles an ask.
*
* `next(e)` resolves to the engine's verdict (rules, mode, the tool's own
* check, PreToolUse's decision); return any `{ decision }`. `$.tool.check`
* runs the same chain and executes nothing.
*
* @example
* on("tool.check", { tool: "Read" }, () => ({ decision: "allow" }))
*/
'tool.check': ToolCheckInput;
/**
* Fires when the engine is about to draw a component: once per input value
* (props, viewport width), plugin load or `$.ui.invalidate("ui.render")`.
*
* A repaint reuses the answer; a clock invalidates. `next(e)` resolves to the
* drawing: return it, wrap it, draw your own, or rewrite `props`. A tree that
* does not validate draws the engine's own; `--plugin-dir` is told why.
*/
'ui.render': RenderInput;
/**
* Fires when the plugins load (not per draw), once per surface, component
* and plugin: `e` names the surface and component, never the props.
*
* `next(e)` resolves to the surface's table, which `$.ui.resolve(e)` then
* reads. Return it, one with an element restyled for every other plugin,
* or one with a key left out (a fragment there); own table: hook skipped.
*/
'ui.resolve': ResolveInput;
/**
* Fires when a `Button` a render hook drew is pressed on a surface; `e` is
* `{ plugin, element, component, surface }`, `element` the button's `key`.
*
* `next(e)` runs the hooks beneath, then core: the element's own `onPress`
* closure, in its plugin's environment, resolving to `{ element }`. Return
* `next(e)` to let the press through, or `{ element }` to take it.
*/
'ui.press': UiPressArgument;
/**
* Fires when an `Input` a render hook drew changes or is submitted; `e` is
* `{ plugin, element, component, surface, kind, value }`.
*
* `next(e)` runs the hooks beneath, then the element's own `onInput` or
* `onSubmit` with `e.value` as the chain left it, resolving to `{ element,
* value }`; `next({ ...e, value })` rewrites the typing, an answer takes it.
*/
'ui.input': UiInputArgument;
/**
* Fires when a `Select` a render hook drew is picked from; `e` is
* `{ plugin, element, component, surface, value }`.
*
* `next(e)` runs the hooks beneath, then the element's own `onSelect` with
* `e.value` as the chain left it, resolving to `{ element, value }`;
* `next({ ...e, value })` rewrites the pick, an answer takes it.
*/
'ui.select': UiSelectArgument;
/**
* Fires when a `Client` THIS plugin drew posts from its surface module
* (`surface.post(data)`); only this plugin's hooks see it.
*
* `next.origin` names `client`: `data` came from code. Core answers `{}`;
* `next({ ...e, data })` rewrites the data; `{ props }` hands the posting
* instance its next props without a redraw. One per instance per frame.
*/
'ui.message': UiMessageArgument;
/**
* Fires before a site's window moves: the person's wheel or scroll keys on
* a `Pane` body or the `AbovePrompt` band, at its edges too; `$.ui.scroll`.
*
* `next(e)` moves it to `e.offset` and draws: `{}`; `next({ ...e, offset
* })` elsewhere; no `next` (`{}` or `{ deny }`) leaves it undrawn, so a hook
* drawing its own rows under a header moves them by `e.by` and invalidates.
*
* @example
* on("ui.scroll", { requestId: "log" }, ($, e) => (scrollOwnRows(e.by), {}))
*/
'ui.scroll': UiScrollInput;
/**
* Fires before a site's focus ring moves: the person's Tab, arrows or click
* in a `Pane` or the band; an `autoFocus` element taking it; `$.ui.focus`.
*
* `next(e)` lands it on `e.element` (absent: one of the engine's stops) and
* draws: `{}`; `next({ ...e, element })` on another of `e.plugin`'s; no
* `next` (`{}` or `{ deny }`) keeps it where it was, drawn as it was.
*
* @example
* on("ui.focus", { requestId: "list" }, ($, e, next) => (mark(e), next(e)))
*/
'ui.focus': UiFocusInput;
/**
* Fires when the engine offers an agent type to the model, in the agent
* listing and again at dispatch; `next(e)` resolves to `{ isOffered: true }`.
*
* Return `{ isOffered: false }` to keep the type out of the listing and
* refuse its dispatch. A hook that fails passes it through.
*
* @example
* on("agent.offer", { agent: "Plan" }, () => ({ isOffered: false }))
*/
'agent.offer': AgentOfferInput;
/**
* Fires when the Agent tool is about to start a subagent, everything
* decided and its model not yet resolved.
*
* `next(e)` resolves to `{ model }`. Return it, `next({ ...e, model })`,
* `{ model }` of your own (an alias resolves like the tool's parameter), or
* `{ deny: reason }`.
*/
'agent.spawn': AgentSpawnInput;
/**
* Fires when a prompt is submitted, before the turn starts. `next(e)` runs
* the hooks beneath and the UserPromptSubmit settings hooks.
*
* Rewrite with `next({ ...e, text })` (the user message on screen follows)
* or stop it with `{ drop: reason }`; a broken plugin never blocks a prompt.
* A prompt typed while a turn ran fires at Enter, with that turn's id.
*/
'prompt.submit': PromptSubmitInput;
/**
* Fires when a text is about to be written into the prompt box as the
* person's draft (a plugin's `$.prompt.fill`); `next(e)` writes it.
*
* Rewrite with `next({ ...e, text })`, or answer `{ isFilled: false }`
* without `next` to keep it out; `origin` passes on as received. Core
* answers `{ isFilled: false }` where no box can take it (a dialog is up).
*
* @example
* on("prompt.fill", ($, e, next) => next({ ...e, text: e.text.trim() }))
*/
'prompt.fill': PromptFillInput;
/**
* Fires when a text is proposed as the prompt box's dim suggestion, Tab to
* take: the engine's guess after a turn, or a plugin's `$.prompt.suggest`.
*
* `next(e)` shows it: `{ isShown }`. Rewrite with `next({ ...e, text })`,
* or answer `{ isShown: false }` without `next` to drop it; core answers
* that too while the box holds text or a turn runs.
*
* @example
* on("prompt.suggest", { origin: { kind: "suggestion" } }, hide)
*/
'prompt.suggest': PromptSuggestInput;
/**
* Fires once per named section of the system prompt, when the engine
* assembles it; `next(e)` resolves to `{ text }` as core computed it.
*
* Sections are cached by name for the session until
* `$.ui.invalidate("prompt.section")`: an unstable answer spends the
* model's prompt cache on every call. A hook that fails passes it through.
*
* @example
* on("prompt.section", { name: "memory" }, () => ({ text: null }))
*/
'prompt.section': PromptSectionInput;
/**
* Fires once per conversation, when the engine computes the context blocks
* its first user message carries; `next(e)` resolves to `{ blocks }`.
*
* Append, drop, reorder or rewrite with `next({ ...e, blocks })`; the
* engine renders what comes back, in order, until
* `$.ui.invalidate("prompt.context")` or a re-read (compaction, `/clear`).
*
* @example
* on("prompt.context", () => ({ blocks: [] }))
*/
'prompt.context': PromptContextInput;
/**
* Fires once per tool, when the engine first renders the tool's schema for
* the model in a session; `next(e)` resolves to `{ description }`.
*
* Rendered schemas are cached for the session until
* `$.ui.invalidate("tool.describe")`: an unstable answer spends the model's
* prompt cache on every call. A hook that fails passes it through.
*
* @example
* on("tool.describe", { tool: "Bash" }, () => ({ description: "Shell." }))
*/
'tool.describe': ToolDescribeInput;
/**
* Fires when a slash command is about to run (`/name args` typed, or a
* plugin's `$.command.run`); `next(e)` resolves to `{ text }`, its output.
*
* Core is the engine's command (a registered one has none). Rewrite `args`
* with `next`, or return `{ text }` without it to answer in its place; one
* after `next` replaces a printed output, not a panel or prompt it opened.
*
* @example
* on("command.run", { command: "hello" }, () => ({ text: "hello" }))
*/
'command.run': CommandRunInput;
/**
* Fires once per command, when the engine lists it for the typeahead and
* `/help`; `next(e)` resolves to `{ description, argumentHint, isHidden }`.
*
* Listed answers are cached for the session until
* `$.ui.invalidate("command.describe")`. A hook that fails passes it
* through.
*
* @example
* on("command.describe", ($, e, next) => next({ ...e, isHidden: true }))
*/
'command.describe': CommandDescribeInput;
/**
* Fires when a `/config` row is about to change, from the menu or a
* plugin's `$.config.set`; `next(e)` resolves to `{ value }` once written.
*
* Return `{ deny: reason }` to leave the row as it is (the menu says why),
* or `next({ ...e, value })` to clamp it; a value of the wrong kind for
* the row is refused. A row a trusted source owns is core's to refuse.
*
* @example
* on("config.set", { key: "theme" }, () => ({ deny: "the theme stays" }))
*/
'config.set': ConfigSetInput;
/**
* Fires once per `/config` row, when the menu lists it and for
* `$.config.list`; `next(e)` resolves to `{ label, description, isHidden }`.
*
* Relabel, re-describe or hide with `next({ ...e, isHidden: true })`; the
* answers are cached until `$.ui.invalidate("config.describe")` or the
* loaded plugins change. A hook that fails passes the row through.
*
* @example
* on("config.describe", { key: "tips" }, hide) // answers isHidden: true
*/
'config.describe': ConfigDescribeInput;
/**
* Fires when the engine expands a skill's prompt for the model (`/name`,
* the Skill tool, a preload); `next(e)` resolves to `{ text }` as computed.
*
* Return `{ text }` with the text the model reads instead. A hook that
* fails passes it through.
*
* @example
* on("skill.prompt", { skill: "commit" }, () => ({ text: "A haiku." }))
*/
'skill.prompt': SkillPromptInput;
/**
* Fires when the engine composes a git text the model is to write (`kind`:
* `commit`, `pr`, `exemption`, `remedy`); `next(e)` resolves to `{ text }`.
*
* Return `{ text }` with the text the model reads instead. A hook that
* fails passes it through.
*
* @example
* on("attribution.text", { kind: "commit" }, () => ({ text: "" }))
*/
'attribution.text': AttributionTextInput;
/**
* Fires once per process for each loaded plugin, before the first prompt,
* and again for one that loads or reloads later; `next(e)` is `{ cwd }`.
*
* Observe. The first is awaited, so a `$.tool.register` here is listed by
* turn one. A later one (an edit, new options, `/reload-plugins`, an enable)
* runs that plugin's hooks alone, so its timers start again. Not `/clear`.
*
* @example
* on("session.start", ($, e, next) => $.tool.register(t).then(() => next(e)))
*/
'session.start': SessionStartInput;
/**
* Fires when a delivery reaches the session (a relay's event, a peer's
* message, a Remote Control prompt), before it is queued; `{ text }`.
*
* Rewrite with `next({ ...e, text })`, or return `{ consumed: reason }` to
* take it: nothing is queued, shown or read by the model. `origin` and
* `event` pass on as received; `session.send`, its dual, is reserved.
*
* @example
* on("session.receive", { origin: "peer" }, () => ({ consumed: "muted" }))
*/
'session.receive': SessionReceiveInput;
/**
* Fires when the conversation is about to be compacted (`/compact`, the
* threshold, a plugin, or ahead of time); `next(e)` resolves `{ messages }`.
*
* Rewrite `instructions` or `messages` on the way down, the messages on
* the way up, or answer `{ messages }` of your own; `{ skip: reason }`
* leaves the conversation as it is. `trigger` passes on as received.
*
* @example
* on("session.compact", { trigger: "precompute" }, () => ({ skip: "off" }))
*/
'session.compact': SessionCompactInput;
/**
* Fires when a remote client joins the session's roster of attached
* surfaces: it said so (ui_attach), or it first asked to draw.
*
* Observe (a phone joined: draw the lobby); `next(e)` resolves to
* `{ clientId }`, a different return changes nothing. `$.session.surfaces()`
* reads the roster; a render hook still reads `e.surface` per ask.
*
* @example
* on("session.attach", { surface: "mobile" }, ($, e, next) => next(e))
*/
'session.attach': SessionAttachInput;
/**
* Fires when a client leaves the roster: it detached, or the session ended
* with it attached (`e.reason`). Observe; `next(e)` echoes `{ clientId }`.
*/
'session.detach': SessionDetachInput;
/**
* Fires once per hooks module about to join the chain, at load (the set
* folded and built, nothing swapped in) and at reload; core allows.
*
* Return `{ refuse: reason }` and it never joins: no hook, no noun, no tool
* of it; the transcript names who refused. Its judges, `$` whole, are the
* plugins admitted before it and the binary's; judge by `tier` and `uses`.
*
* @example
* on("plugin.register", { tier: "user" }, () => ({ refuse: "managed only" }))
*/
'plugin.register': PluginRegisterInput;
/**
* Fires when a model turn begins, before its first model call; `next(e)`
* resolves to `{ turnId }`. Observe: a different return changes nothing.
*/
'turn.start': TurnStartInput;
/**
* Fires when the engine is about to send a model request of a turn, main's
* or a subagent's (`e.agentId`); `next(e)` resolves to the whole response.
*
* `next({ ...e, model })` or `effort` sends another; the turn, the index and
* the message count are pinned. An answer without `next` sends no request.
* Every request of the turn passes here; `turn.complete` follows the last.
*/
'turn.step': TurnStepInput;
/**
* Fires when a model turn has ended, at the point its duration is reported;
* `next(e)` resolves to `{ text }`, the answer. `e.reason` says why.
*
* Return `{ text }` with a different text to show it beneath the answer (a
* synopsis, a TL;DR line); the transcript's record is never rewritten. A
* hook that fails leaves the answer as it was.
*/
'turn.complete': TurnCompleteInput;
/**
* Runs while `$` is being built, once per load or reload of this plugin
* and before any other hook of it; `next(e)` resolves to `$` built so far.
*
* A step may ADD nouns and WITHHOLD nouns (leave one out, or return without
* `next`); it may NOT REPLACE one another step added: the step fails, named
* with both plugins. A step that fails unloads its plugin; `$` is rebuilt.
*/
'engine.create': EngineCreateInput;
};
/**
* `$`, the first parameter of every hook. Frozen; core's interface plus
* every noun the plugins' `engine.create` steps added.
*
* Flat, `<noun>.<event>`; it does not carry `on`, since registration happens
* before `$` exists. An interface so a plugin types the noun it provides by
* declaration merging, the way a jQuery plugin types `$.fn`.
*
* @example
* declare module "claude-code" { interface EngineInterface { voice: Voice } }
*/
export interface EngineInterface extends CoreEngineInterface {
}
/**
* What `next(e)` resolves to at `engine.create`: `$` as the steps beneath
* built it, typed as `$` is, open to nouns no declaration names yet.
*
* A withheld noun is on it as a stub (a step inside withheld it, or the
* last fold did and this is a reload), and the host refuses an op on one a
* step outside withholds later; a typed module bootstraps at load on it.
*/
export type EngineInterfaceBuilt = EngineInterface & {
readonly [noun: string]: unknown;
};
/**
* The engine's events' results.
*/
export type EngineResultOf = {
/**
* `{ result, context? }`, `{ deny }`, or core's `{ ref, result }`.
*/
'tool.call': ToolCallResult;
/**
* `{ decision, reason?, rule? }`.
*/
'tool.check': ToolCheckResult;
/**
* The tree to draw; `{ type: "engine", ref }` is core's own drawing.
*/
'ui.render': RenderElement;
/**
* The surface's element table (Elements[e.surface]): constructors from props
* to a RenderElement.
*/
'ui.resolve': ElementTable;
/**
* `{ element }`: the element whose handler the press reached.
*/
'ui.press': UiPressResult;
/**
* `{ element, value }`: the field whose handler the input reached, and
* the text it received.
*/
'ui.input': UiInputResult;
/**
* `{ element, value }`: the picker whose handler the pick reached, and
* the value it received.
*/
'ui.select': UiSelectResult;
/**
* `{ props? }`: the posting instance's next props, when a hook hands some.
*/
'ui.message': UiMessageResult;
/**
* `{}` once the window moved, or `{ deny }`.
*/
'ui.scroll': UiScrollResult;
/**
* `{}` once the ring moved, or `{ deny }`.
*/
'ui.focus': UiFocusResult;
/**
* `{ isOffered }`.
*/
'agent.offer': AgentOfferResult;
/**
* `{ model }` or `{ deny }`.
*/
'agent.spawn': AgentSpawnResult;
/**
* `{ text, context? }` or `{ drop }`.
*/
'prompt.submit': PromptSubmitResult;
/**
* `{ isFilled }`.
*/
'prompt.fill': PromptFillResult;
/**
* `{ isShown }`.
*/
'prompt.suggest': PromptSuggestResult;
/**
* `{ text }` (null leaves the section out).
*/
'prompt.section': PromptSectionResult;
/**
* `{ blocks }` (a block left out is not sent).
*/
'prompt.context': PromptContextResult;
/**
* `{ description }`.
*/
'tool.describe': ToolDescribeResult;
/**
* `{ text }` (the command's output, when it printed one).
*/
'command.run': CommandRunResult;
/**
* `{ description, argumentHint, isHidden }`.
*/
'command.describe': CommandDescribeResult;
/**
* `{ value }` once written, or `{ deny }`.
*/
'config.set': ConfigSetResult;
/**
* `{ label, description, isHidden }`.
*/
'config.describe': ConfigDescribeResult;
/**
* `{ text }`.
*/
'skill.prompt': SkillPromptResult;
/**
* `{ text }`.
*/
'attribution.text': AttributionTextResult;
/**
* `{ cwd }`.
*/
'session.start': SessionStartResult;
/**
* `{ text }`, or `{ consumed }`.
*/
'session.receive': SessionReceiveResult;
/**
* `{ messages, tokensBefore?, tokensAfter? }`, or `{ skip }`.
*/
'session.compact': SessionCompactResult;
/**
* `{ clientId }`.
*/
'session.attach': SessionAttachResult;
/**
* `{ clientId }`.
*/
'session.detach': SessionDetachResult;
/**
* `{ allow: true }`, or `{ refuse }`.
*/
'plugin.register': PluginRegisterResult;
/**
* `{ turnId }`.
*/
'turn.start': TurnStartResult;
/**
* The response: `{ turnId, index, answer, toolUses, stopReason, usage }`.
*/
'turn.step': TurnStepResult;
/**
* `{ text }`.
*/
'turn.complete': TurnCompleteResult;
/**
* `$` as built so far, with this plugin's interface added and any it
* withheld left out; `next(e)` resolves to EngineInterfaceBuilt.
*/
'engine.create': EngineCreateResult;
};
/**
* The engine's own events as calls on `$`, one signature each:
* `$.<noun>.<event>(input)` resolves to its result, or to its stream.
*
* The engine raises its events through these same calls; a plugin's call
* runs the same chain with the calling hook alone skipped. `input` may leave
* out what the engine fills (`tool_use_id`, the parent agent).
*/
export type EventCalls = {
tool: {
call: ToolCallOverloads;
check: (input: ToolCheckArgs) => Promise<ToolCheckResult>;
describe: (input: ToolDescribeInput) => Promise<ToolDescribeResult>;
};
command: {
run: (input: CommandRunArgs) => Promise<CommandRunResult>;
describe: (input: CommandDescribeInput) => Promise<CommandDescribeResult>;
};
config: {
set: (input: ConfigSetArgs) => Promise<ConfigSetResult>;
describe: (input: ConfigDescribeInput) => Promise<ConfigDescribeResult>;
};
prompt: {
submit: (input: PromptSubmitArgs) => Promise<PromptSubmitResult>;
fill: (input: PromptFillArgs) => Promise<PromptFillResult>;
suggest: (input: PromptSuggestArgs) => Promise<PromptSuggestResult>;
section: (input: PromptSectionInput) => Promise<PromptSectionResult>;
context: (input: PromptContextInput) => Promise<PromptContextResult>;
};
skill: {
prompt: (input: SkillPromptInput) => Promise<SkillPromptResult>;
};
attribution: {
text: (input: AttributionTextInput) => Promise<AttributionTextResult>;
};
agent: {
offer: (input: AgentOfferInput) => Promise<AgentOfferResult>;
spawn: (input: AgentSpawnArgs) => Promise<AgentSpawnResult>;
};
session: {
start: (input: SessionStartInput) => Promise<SessionStartResult>;
receive: (input: SessionReceiveInput) => Promise<SessionReceiveResult>;
compact: (input?: SessionCompactArgs) => Promise<SessionCompactResult>;
attach: (input: SessionAttachInput) => Promise<SessionAttachResult>;
detach: (input: SessionDetachInput) => Promise<SessionDetachResult>;
};
turn: {
start: (input: TurnStartInput) => Promise<TurnStartResult>;
step: (input: TurnStepInput) => HookStream<TurnStepChunk, TurnStepResult>;
complete: (input: TurnCompleteInput) => Promise<TurnCompleteResult>;
};
ui: {
render: <C extends RenderComponent>(input: RenderInput<C>) => Promise<RenderElement>;
resolve: <E extends ResolveInput>(e: E) => Elements[E['surface']];
scroll: (input: UiScrollArgs) => Promise<UiScrollResult>;
focus: (input: UiFocusArgs) => Promise<UiFocusResult>;
};
};
/**
* The name of an event: a key of EventOf, the engine's own (CoreEventName)
* and the declared plugin nouns' (NounEventName).
*/
export type EventName = keyof EventOf;
/**
* The argument of each event, by event name: what a hook receives as `e`
* and what the call on `$` takes. Plain data, frozen to every depth.
*
* The engine's own events (CoreEventOf: a plugin's `$.fs.write(...)` is
* a dispatch the hooks above it see) and the methods of the plugin nouns
* declared on EngineInterface (NounEventOf).
*/
export type EventOf = CoreEventOf & NounEventOf;
/**
* The result of event `N`: what its hooks return and what their `next(e)`
* resolves to.
*/
export type EventResult<N extends EventName = EventName> = ResultOf[N];
/**
* The hook signature of each event, `($, e, next)`, as one mapped type over
* EventOf; a streaming event's is the generator form (StreamHook).
*
* With one handler type per event, `Events[E]` for a generic E would be a
* union; as one mapped type it stays a single function type the engine
* calls without a cast (TS 4.6 correlated unions).
*
* @param $ the engine interface, frozen, the same object at every invocation;
* at `engine.create` the empty table, since `$` exists after the fold
* @param e the event's argument, frozen to every depth (`e.command = "ls"`
* is a type error and throws); a rewrite is a copy passed to `next`
* @param next the rest of the chain; a chain a hook raises through `$` skips
* this hook and runs every other, its plugin's others too
*/
export type Events = {
[E in keyof EventOf]: E extends StreamingEventName ? StreamHook<E> : ($: E extends 'engine.create' ? NoEngineInterface : EngineInterface, e: Frozen<Args<E>>, next: Next<E>) => EventResult<E> | Promise<EventResult<E>>;
};
type ExitReason = 'clear' | 'resume' | 'logout' | 'prompt_input_exit' | 'other';
type FileChangedHookInput = BaseHookInput & {
hook_event_name: 'FileChanged';
file_path: string;
event: 'change' | 'add' | 'unlink';
};
/**
* `T` with every property read-only to every depth, arrays and tuples kept
* as declared: how a hook's `e` is typed.
*
* `e.command = 'x'` is a type error; `next({ ...e, command: 'x' })` compiles.
*/
export type Frozen<T> = T extends (...args: never[]) => unknown ? T : T extends readonly unknown[] ? {
[K in keyof T]: Frozen<T[K]>;
} : T extends object ? {
readonly [K in keyof T]: Frozen<T[K]>;
} : T;
/**
* One file `$.fs.ancestors` found: the directory it stands in, the name it
* was asked for by, and its text as the engine's memory loader reads it.
*/
export type FsAncestor = {
/**
* The directory the file stands in, absolute.
*/
dir: string;
/**
* The spelling the caller asked for it by.
*/
name: string;
/**
* The file's text, with what its `@include`s bring after it.
*/
content: string;
};
/**
* The argument of `$.fs.ancestors`: the file names to look for in each
* directory, and the file to walk down to.
*/
export type FsAncestorsRequest = {
/**
* Relative `.md` file names, each looked for in every directory.
*/
names: readonly string[];
/**
* The file the walk goes on down to the directory of, relative to the
* working directory or absolute; absent, it ends at the working directory.
*/
of?: string;
};
/**
* One entry of `$.fs.list`.
*/
export type FsEntry = {
/**
* The entry's name (no directory part).
*/
name: string;
/**
* `file`, `dir`, or `other`.
*/
kind: 'file' | 'dir' | 'other';
/**
* Bytes, for a file.
*/
size: number;
};
/**
* What `$.fs.stat` resolves with.
*/
export type FsStat = {
/**
* `file`, `dir`, or `other`.
*/
kind: 'file' | 'dir' | 'other';
/**
* Bytes, for a file.
*/
size: number;
/**
* Last modification, milliseconds since the epoch.
*/
mtimeMs: number;
};
/**
* Every event (`*`), or every event under a namespace (`classic.*`: each
* one whose name starts with `classic.`).
*/
export type Glob = '*' | `${Namespace}.*`;
/**
* The hook `on(pattern, hook)` takes for a glob or a negation: one function
* placed on every selected event, `e` and the result typed as their union.
*
* `next.event` says which event a run is; `next.is(pattern, e)` narrows `e`
* to one of them. At `engine.create` (a negation may select it) `$` is the
* empty table and the hook observes the fold, as a `*` hook does.
*/
export type GlobHook<P extends Pattern, N extends EventName = Selected<P>> = ($: EngineInterface, e: Frozen<Args<N>>, next: GlobNext<P>) => EventResult<N> | Promise<EventResult<N>>;
/**
* `next` in a hook on a glob or a negation: an overload per selected event,
* then one over their union for an `e` not yet narrowed.
*
* `is` narrows `e` to the selected events its pattern names; `event` is one
* of the selected names.
*/
export type GlobNext<P extends Pattern, N extends EventName = Selected<P>> = OrderedOverloads<N> & {
(e: Args<N>): Promise<GlobNextResult<N>>;
/**
* Continues this dispatch at a tier, as Next's `to` (a managed hook's),
* over the selected events' union for an `e` not yet narrowed.
*/
readonly to: (e: Args<N>, tier: TargetTier) => Promise<GlobNextResult<N>>;
readonly signal: AbortSignal;
readonly is: <M extends PatternOver<N>>(pattern: M, e: unknown) => e is Frozen<Args<Extract<N, Selected<M>>>>;
readonly event: N;
readonly origin: Origin;
readonly trace: readonly TraceEntry<N, Args<N>, GlobNextResult<N>>[];
};
/**
* What `next(e)` resolves to in a glob hook before `e` is narrowed: the
* NextResult of each selected event, as a union.
*/
type GlobNextResult<N extends EventName> = {
[K in N]: NextResult<K>;
}[N];
/**
* One hook, `($, e, next)`, on event `E`.
*/
export type Hook<E extends EventName = EventName> = Events[E];
/**
* Why a hook failed, as its `.catch` handler reads it on `next.error`: plain
* frozen data.
*
* `throw`: the hook threw, or returned what the site refuses, `message`
* saying what; `timeout`: it outran its budget, `message` then what its last
* `next()` rejected with, if it did. `budget` is the handler's own grace.
*/
export type HookFailure = {
readonly kind: 'throw' | 'timeout';
/**
* The thrown error's message, or for a timeout what the hook's last
* `next()` rejected with; absent for a timeout with nothing rejected.
*/
readonly message?: string;
/**
* The grace the handler runs under, in milliseconds; past it, the hook is
* absent as if it had no handler.
*/
readonly budget: number;
};
/**
* The hook type per pattern: an event's own (Events), `*`'s (AnyEventHook),
* or a glob's over the events it selects (GlobHook), as one conditional type.
*
* One type, so the two-argument `on` stays ONE generic signature: as an
* overload set the language service offers no tool-name completions inside
* `e.tool === "`; as an index into a table TS intersects every argument.
*/
export type HookFor<P extends Pattern> = P extends '*' ? AnyEventHook : P extends EventName ? Events[P] : GlobHook<P>;
type HookInput = PreToolUseHookInput | PostToolUseHookInput | PostToolUseFailureHookInput | PostToolBatchHookInput | PermissionDeniedHookInput | NotificationHookInput | UserPromptSubmitHookInput | UserPromptExpansionHookInput | SessionStartHookInput | SessionEndHookInput | StopHookInput | StopFailureHookInput | SubagentStartHookInput | SubagentStopHookInput | PreCompactHookInput | PostCompactHookInput | PreModelSwitchHookInput | PostModelSwitchHookInput | PermissionRequestHookInput | SetupHookInput | TeammateIdleHookInput | TaskCreatedHookInput | TaskCompletedHookInput | ElicitationHookInput | ElicitationResultHookInput | ConfigChangeHookInput | InstructionsLoadedHookInput | WorktreeCreateHookInput | WorktreeRemoveHookInput | CwdChangedHookInput | FileChangedHookInput | DirectoryAddedHookInput | MessageDisplayHookInput;
/**
* The hook event `E` takes: an async generator over its chunks for a
* streaming event (`turn.step`), `($, e, next) => result` for every other.
*/
export type HookOf<E extends EventName> = Events[E];
/**
* What a hooks module exports: `register`, and nothing the loader reads
* besides.
*/
export type HooksModule = {
register: Register;
};
/**
* What `next(e)` returns on a streaming event: the stream of everything
* beneath, chunk by chunk, whose return value is the result from beneath.
*
* `yield* next(e)` forwards the chunks and evaluates to that result; a
* transforming hook reads `for await (const chunk of stream)` and then
* `await stream.result`. Each call runs what is beneath afresh.
*/
export type HookStream<C, R> = AsyncGenerator<C, R> & {
/**
* Settles with what beneath returned once the stream has been read to
* its end; rejects if the stream is closed before that.
*/
readonly result: Promise<R>;
};
/**
* Options of `$.http.fetch`.
*/
export type HttpInit = {
/**
* `GET` (default), `POST`, ...
*/
method?: string;
/**
* Request headers.
*/
headers?: Record<string, string>;
/**
* The request body, as text.
*/
body?: string;
/**
* The handle `$.session.authorize()` answered: the engine sets the
* session's credential header itself, only for a first-party host.
*/
auth?: string;
};
/**
* What `$.http.fetch` resolves with.
*/
export type HttpResponse = {
/**
* The HTTP status code.
*/
status: number;
/**
* True for a 2xx status.
*/
ok: boolean;
/**
* Response headers, lower-cased names.
*/
headers: Record<string, string>;
/**
* The body, as text.
*/
text: string;
};
/**
* The keys of object pattern `P` that object member `E` cannot satisfy, `D`
* levels down; `never` when there is none, which is what keeps the member.
*
* A key `E` does not have (an open record has every string key), or one
* whose value `P` narrows to nothing.
*/
type ImpossibleKeys<E, P, D extends readonly unknown[]> = {
[K in keyof P]-?: K extends keyof E ? [NarrowedValue<Exclude<E[K], undefined>, P[K], D>] extends [never] ? K : never : K;
}[keyof P];
/**
* The props of `Input`, every surface's one-line text field: an address,
* optional texts, and the closures a change and a submit run. A leaf.
*
* Focused through the same ring as `Button` (`abovePrompt:focus`); while it
* has focus every printable key reaches it alone and Esc returns them; a
* change and Enter raise `ui.input`, whose bottom is `onInput` / `onSubmit`.
*/
export type InputProps = {
/**
* The element's address: `e.element` at `ui.input`, what a matcher names.
*/
key: string;
/**
* Text drawn before the field.
*/
label?: string;
/**
* Text drawn dim in an empty field.
*/
placeholder?: string;
/**
* The text the field holds when drawn; the person's typing replaces it
* until the hook draws another.
*/
value?: string;
/**
* What Enter does, in a word or two, drawn beside the field while it has
* focus (`send`). Defaults to `submit`.
*/
submitLabel?: string;
/**
* The site's focus ring starts here when the site takes the keyboard,
* instead of on nothing, as the DOM's `autofocus`: Enter acts on it at once.
*
* A pane opened with `focus`, or the person's focus chord or click, is the
* take. Of several in one site the first drawn wins; it raises `ui.focus`,
* origin this plugin. A ring the person has moved stays where it was put.
*/
autoFocus?: true;
/**
* Runs on every change of the text, in the plugin's own environment: the
* bottom of a `ui.input` chain of kind `change`.
*/
onInput?: (value: string, e: UiInputArgument) => void;
/**
* Runs on Enter with the text, in the plugin's own environment: the bottom
* of a `ui.input` chain of kind `submit`. No model turn unless it asks one.
*/
onSubmit: (value: string, e: UiInputArgument) => void;
};
type InstructionsLoadedHookInput = BaseHookInput & {
hook_event_name: 'InstructionsLoaded';
file_path: string;
memory_type: 'User' | 'Project' | 'Local' | 'Managed';
load_reason: 'session_start' | 'nested_traversal' | 'path_glob_match' | 'include' | 'compact';
globs?: string[];
trigger_file_path?: string;
parent_file_path?: string;
};
/**
* What `$.ui.invalidate` takes: a render event, or one of the five events
* whose answers the engine caches for the session.
*/
export type InvalidatableEventName = RenderEventName | 'prompt.section' | 'prompt.context' | 'tool.describe' | 'command.describe' | 'config.describe';
/**
* Whether tag key `K` selects members of `I`: it does when each member gives
* it ONE literal (`component: "ToolUse"` on the ToolUse variant).
*
* A key that is the same union on every member is a filter at runtime; it
* is left out of the selection so that it cannot defeat the narrowing the
* other keys give.
*/
type IsDiscriminant<I, K> = I extends unknown ? K extends KnownKeys<I> ? IsSingleLiteral<I[K]> : true : never;
/**
* Whether `V` is made of literals only: `"a" | "b"` is, `string` is not.
*/
type IsLiteralValued<V> = string extends V ? false : number extends V ? false : boolean extends V ? false : [V] extends [string | number | boolean] ? true : false;
/**
* Whether `V` is exactly one string, number or boolean literal.
*/
type IsSingleLiteral<V> = [V] extends [string | number | boolean] ? IsUnion<V> extends true ? false : true : false;
/**
* Whether `T` is a union of two or more members.
*/
type IsUnion<T, U = T> = T extends unknown ? [U] extends [T] ? false : true : never;
/**
* Plain data: what JSON holds, and what crosses between a plugin's hooks
* module and its surface module whole (a `Client`'s props, a post's data).
*
* A function, a class instance, `undefined` or a cycle is not plain data;
* the engine refuses one where it checks, and drops it where it clones.
*/
export type JsonValue = string | number | boolean | null | readonly JsonValue[] | {
readonly [key: string]: JsonValue;
};
/**
* What `next` takes in a matched hook: the variants of `e` the matcher can
* match (KeptMembers), as declared, so a rewrite of a pinned field passes.
*/
type KeptEvent<P extends Pattern, M> = MatchedNames<P, M> extends infer N extends EventName ? N extends unknown ? KeptMembers<Args<N>, M> : never : never;
/**
* The members of the argument union `E` matcher `P` can match, as declared;
* what `next` takes, so a rewrite may change a field the matcher pinned.
*
* A member is dropped when `P` names a key it lacks, or gives a key, at any
* depth, a value none of that key's values can equal (ImpossibleKeys).
*/
type KeptMembers<E, P> = E extends unknown ? [ImpossibleKeys<E, P, []>] extends [never] ? E : never : never;
/**
* The declared keys of `T`, the string and number index signatures left out.
*/
type KnownKeys<T> = keyof {
[K in keyof T as string extends K ? never : number extends K ? never : K]: 0;
};
/**
* The events whose overload must come after the rest, lest it shadow them.
*
* `classic.PreToolUse` shares `tool.call`'s envelope, `turn.abort` every
* turn event's `turnId`, and an object of any shape is assignable to NoArgs.
*/
type LateOverload = 'classic.PreToolUse' | 'turn.abort' | NoArgsEvent;
/**
* The props of `Link`, a hyperlink every surface draws: an OSC 8 span on the
* terminal (else its text then the URL in dim), an anchor on desktop.
*
* An inline element: its children are the text, strings and inline
* elements; absent children the `label`, absent both the URL. The engine
* bounds `href` before the tree crosses.
*/
export type LinkProps = {
/**
* Where the link goes: an `https:` URL (or `http://localhost`), at most
* 2048 characters of printable ASCII, spelled as `new URL(href).href`.
*
* No `user@host` part, no raw `@`, space or non-ASCII letter (encode them);
* anything else refuses the tree the Link is in.
*/
href: string;
/**
* The text drawn when the element has no children; absent both, the URL
* itself is the text.
*/
label?: string;
};
/**
* What a matcher value selects by: itself, or `unknown` for a RegExp, which
* selects nothing.
*/
type Literal<X> = X extends RegExp ? unknown : X;
/**
* The argument a matched hook receives: `e` narrowed by `M` (Narrowed), per
* event the registration covers.
*/
export type MatchedEvent<P extends Pattern, M> = MatchedNames<P, M> extends infer N extends EventName ? N extends unknown ? Narrowed<Args<N>, M> : never : never;
/**
* The hook `on(pattern, matcher, hook)` takes: `($, e, next)` with `e`
* narrowed by the matcher (MatchedEvent), and a tagged result the same way.
*
* On a streaming event it is the generator form (MatchedStreamHook). `next`
* takes the variants the matcher keeps, as declared (KeptEvent); `next.is`
* names the events the registration covers and narrows as the matcher does.
*/
export type MatchedHook<P extends Pattern, M> = P extends StreamingEventName ? MatchedStreamHook<P, M> : ($: EngineInterface, e: Frozen<MatchedEvent<P, M>>, next: Next<MatchedNames<P, M>, KeptEvent<P, M>, MatchedResult<P, M>, {
[K in MatchedNames<P, M>]: Narrowed<Args<K>, M>;
}>) => MatchedResult<P, M> | Promise<MatchedResult<P, M>>;
/**
* The events a matched registration on `P` covers: the event named, or for a
* glob every selected event whose input has each key the matcher names.
*/
type MatchedNames<P, M = never> = P extends EventName ? P : {
[N in Selected<P & string>]: [M] extends [never] ? N : keyof M extends AnyKeyOf<Args<N>> ? N : never;
}[Selected<P & string>];
/**
* What a matched hook returns: the event's result, narrowed by `M` where the
* result is a union tagged by the matcher's tag keys.
*/
export type MatchedResult<P extends Pattern, M> = MatchedNames<P, M> extends infer N extends EventName ? N extends unknown ? Select<EventResult<N>, Selection<Args<N>, M>> : never : never;
/**
* The hook `on(event, matcher, hook)` takes on a streaming event: the
* generator form, `e` narrowed by the matcher, `next(e)` the stream beneath.
*/
export type MatchedStreamHook<P extends StreamingEventName, M> = ($: EngineInterface, e: Frozen<MatchedEvent<P, M>>, next: MatchedStreamNext<P, M>) => StreamHookBody<Chunk<P>, MatchedResult<P, M>>;
/**
* What a matched streaming hook's `next.is(pattern, e)` narrows `e` to:
* the streaming event's argument narrowed by the matcher.
*/
type MatchedStreamNarrowings<P extends StreamingEventName, M> = {
[K in P]: Narrowed<Args<K>, M>;
};
/**
* A matched streaming hook's `next`: the variants the matcher keeps, the
* result tagged the same way, `next.is` narrowing as the matcher does.
*/
type MatchedStreamNext<P extends StreamingEventName, M> = StreamNext<P, KeptEvent<P, M>, MatchedResult<P, M>, MatchedStreamNarrowings<P, M>>;
/**
* What `on(event, matcher, hook)` takes for an argument of type `I`: the
* shape of the `e` the hook wants, a partial of it at any depth.
*
* A leaf is `===` or a RegExp (`{ command: /^p4 / }`); an array is any-of;
* an object is a partial of an OBJECT, so `{ command: { startsWith } }` is
* a type error where `e` is typed and free where it is `unknown`.
*/
export type Matcher<I, All = I> = I extends unknown ? {
readonly [K in KnownKeys<I>]?: MatcherValue<I[K], MatcherValueOf<All, K>>;
} & (string extends keyof I ? OpenMatcher<I, All> : unknown) : never;
/**
* Any matcher at all, for a field typed `unknown` (a tool's input, a
* result's output): the kinds the engine accepts, unchecked there.
*
* The four kinds: a scalar is `===`; a RegExp tests the value as a string
* (`{ command: /^p4 / }`); an array matches if any element does; an object
* is a partial of an object. `{ startsWith: 'p4' }` never matches a string.
*/
type MatcherData = string | number | boolean | null | RegExp | readonly MatcherData[] | {
readonly [key: string]: MatcherData;
};
/**
* The declared keys of every variant of `I` (index signatures aside).
*/
type MatcherKeys<I> = I extends unknown ? KnownKeys<I> : never;
/**
* What matches one value of type `V`, by the runtime's kinds:
* a scalar leaf takes the value or a RegExp; an object, a partial of it.
*
* For an array, what matches one ELEMENT of it, since a pattern against an
* array value holds when some element matches; for `unknown`, any matcher.
* A scalar matches by `===`, a RegExp tests the value as a string.
*/
type MatcherOne<V> = unknown extends V ? MatcherData : V extends readonly (infer Item)[] ? MatcherOne<Item> : V extends string | number | boolean | null ? V | RegExp : V extends object ? Matcher<V> : V extends undefined ? never : unknown;
/**
* What a matcher gives a key whose value is `V` on this variant and `Across`
* over every variant: one MatcherOne, or an array of them matched as one-of.
*
* The one-of is typed over every variant, so `{ tool: ['Bash', 'Read'] }`
* types on the Bash variant; with a nested pattern beside it, the pattern is
* checked against a variant the one-of names, not against each of them.
*/
type MatcherValue<V, Across = V> = MatcherOne<V> | readonly MatcherOne<Across>[];
/**
* The type of key `K` across the variants of `I` that declare it.
*/
type MatcherValueOf<I, K> = I extends unknown ? K extends KnownKeys<I> ? I[K] : never : never;
/**
* One block of an MCP result: `type` and the fields that kind of block carries.
*/
export type McpContentBlock = {
/**
* The block's kind: `text`, `image`, `audio`, `resource`, `resource_link`.
*/
type: string;
/**
* Set on a `text` block.
*/
text?: string;
/**
* Set on a `resource_link` (or embedded `resource`) block.
*/
uri?: string;
/**
* Declared by an image, audio or resource block.
*/
mimeType?: string;
[field: string]: unknown;
};
/**
* The MCP branch: one variant per declared tool when McpToolInputs has
* entries, else one loose variant over every `mcp__*` name.
*/
export type McpToolCallInput = [keyof McpToolInputs] extends [never] ? McpToolCallInputFallback : {
[N in keyof McpToolInputs & string]: ToolInputOf<N, McpToolInputs[N] & Record<string, unknown>>;
}[keyof McpToolInputs & string];
/**
* The MCP branch's answer when no MCP tool is declared: every `mcp__*`
* name, its args unconstrained.
*/
type McpToolCallInputFallback = {
/**
* The name of the tool being called (`mcp__<server>__<tool>`); comparing
* it narrows `e`. Reserved: a rewrite of it is ignored by core.
*/
tool: McpToolName;
/**
* The tool_use block's id: the same at every event of the call and in
* `$.ui.notice`. Reserved: a rewrite of it is ignored by core.
*/
tool_use_id: string;
[argument: string]: unknown;
};
/**
* The inputs of the MCP tools this project knows, keyed by full tool name,
* for declaration merging; empty by default, then every MCP tool is loose.
*
* A `.d.ts` in the plugin author's project (written by `/plugin-types <dir>`
* from the connected servers' JSON Schemas, or by hand) adds entries under
* `declare module "claude-code"`; `e.tool === <name>` then narrows to them.
*
* @example
* interface McpToolInputs { "mcp__my_server__send": { to: string } }
*/
export interface McpToolInputs {
}
/**
* The name of an MCP tool as the engine spells it: `mcp__<server>__<tool>`.
*/
export type McpToolName = `mcp__${string}__${string}`;
/**
* An MCP tools/call result as the SDK returns it, plain data.
*/
export type McpToolResult = {
/**
* The result's content blocks, in order (text, image, resource,
* resource_link, ...).
*/
content: McpContentBlock[];
/**
* True when the server reported the call as failed; the blocks then describe
* the error.
*/
isError: boolean;
/**
* The server's structured result, when its tool declares an output schema.
*/
structuredContent?: unknown;
};
/**
* Hook input for the MessageDisplay event. Fired with each batch of newly completed lines while an assistant message streams. Display-only: the stored message and what the model sees are untouched.
*/
type MessageDisplayHookInput = BaseHookInput & {
hook_event_name: 'MessageDisplay';
/**
* UUID of the current turn.
*/
turn_id: string;
/**
* UUID of the assistant message being displayed. Stable across every flush of the same message. Not the API msg_... id.
*/
message_id: string;
/**
* Zero-based index of this delta within the message. Increments by one per flush.
*/
index: number;
/**
* True on the message's last flush. Exactly one flush per message has it.
*/
final: boolean;
/**
* The newly completed lines since the prior flush. Always whole lines, except on the final flush which may end mid-line. The delta of the final flush is empty when the message ends on a newline; treat final as the end-of-message signal regardless.
*/
delta: string;
};
/**
* What `$.model.complete` takes.
*/
export type ModelCompleteRequest = {
/**
* An alias (`haiku`) or a full model id; resolved and allowlist-checked like
* a `--model` value.
*/
model: string;
/**
* The one user message; the reply's text comes back.
*/
prompt: string;
/**
* Precedes the completion as its system prompt, after the CLI's identity
* block. Default none.
*/
system?: string;
/**
* The reply's token cap. Default 256.
*/
maxTokens?: number;
};
/**
* What `$.model.fork` takes.
*/
export type ModelForkRequest = {
/**
* The one user message, appended to the session's own transcript.
*
* The reply's text and usage come back, or null on an API error or a cold
* transcript.
*/
prompt: string;
};
/**
* What `$.model.fork` resolves to when the fork answered: the reply's text
* and what the fork cost.
*/
export type ModelForkResult = {
/**
* The non-error replies' text, joined by newlines.
*/
text: string;
/**
* The fork's token counts, so a plugin can account for what it spent.
*/
usage: ModelForkUsage;
};
/**
* What one fork cost, as the API counted it: the four token counts of the
* fork's completions summed.
*/
export type ModelForkUsage = {
input_tokens: number;
output_tokens: number;
cache_read_input_tokens: number;
cache_creation_input_tokens: number;
};
/**
* The prefixes a glob may name: one or more whole leading segments of an
* event name (`tool` of `tool.call`), derived, plugin nouns included.
*/
export type Namespace<N extends string = EventName> = N extends `${infer Head}.${infer Rest}` ? Head | `${Head}.${Namespace<Rest>}` : never;
/**
* How many object or array levels a matcher narrows `e` through, counted as
* a tuple's length: the runtime's own limit, which refuses a deeper matcher.
*
* Past it a field keeps its declared type; nothing becomes `any`.
*/
type NarrowDepth = 8;
/**
* `e` in a matched hook: the members of the argument union `E` matcher `P`
* can match, each with the keys `P` names narrowed to what a match implies.
*
* A scalar narrows to the literal, a one-of to what its alternatives give,
* an object key recursively, an array some element of which must match to
* a non-empty tuple; other keys, `unknown` and RegExp-matched fields keep.
*/
export type Narrowed<E, P> = E extends unknown ? NarrowedMember<E, P, []> : never;
/**
* A value of declared type `V` under a one-of, folded over the tuple into
* `Found`: the union of what each alternative narrows `V` to (NarrowedByOne).
*
* An alternative that cannot match adds nothing, so a one-of none of whose
* alternatives can is `never`; a one-of typed as a plain array rather than
* a tuple narrows by the union of its elements at once.
*/
type NarrowedByAny<V, Alternatives extends readonly unknown[], D extends readonly unknown[], Found = never> = Alternatives extends readonly [infer First, ...infer Rest] ? NarrowedByAny<V, Rest, D, Found | NarrowedByOne<V, First, D>> : Alternatives extends readonly [] ? Found : Found | NarrowedByOne<V, Alternatives[number], D>;
/**
* A value of declared type `V` under one matcher node `Q` that is not a
* one-of, member of `V` by member; a member that cannot match is `never`.
*
* An array some element of which must match becomes NonEmpty; a RegExp
* keeps the member; an object pattern recurses into an object member, one
* level down; a scalar keeps a member as narrow, and replaces a wider one.
*/
type NarrowedByOne<V, Q, D extends readonly unknown[]> = V extends readonly (infer Item)[] ? [NarrowedValue<Item, Q, [...D, unknown]>] extends [never] ? never : NonEmpty<V, Item> : Q extends RegExp ? V : Q extends object ? V extends object ? NarrowedMember<V, Q, [...D, unknown]> : never : V extends Q ? V : Q extends V ? Q : never;
/**
* One object member `E` under object pattern `P`, `D` levels down: `never`
* when a key of `P` is impossible on it (ImpossibleKeys), else `E` narrowed.
*
* Each key `P` names is narrowed (NarrowedValue); every other key, and each
* key's optionality, stays as declared.
*/
type NarrowedMember<E, P, D extends readonly unknown[]> = [
ImpossibleKeys<E, P, D>
] extends [never] ? {
[K in keyof E]: K extends keyof P ? NarrowedValue<E[K], P[K], D> : E[K];
} : never;
/**
* A value of declared type `V` where the matcher gives `Q`, `D` levels
* down: NarrowedByAny under a one-of (an array), NarrowedByOne otherwise.
*
* As declared once `D` reaches NarrowDepth, or for a field typed `unknown`
* (a tool's input), which no pattern narrows.
*/
type NarrowedValue<V, Q, D extends readonly unknown[]> = D['length'] extends NarrowDepth ? V : unknown extends V ? V : Q extends readonly unknown[] ? NarrowedByAny<V, Q, D> : NarrowedByOne<V, Q, D>;
/**
* `!` before a name or a glob: every event except the ones it selects. `!*`
* would select none, so it is no pattern.
*/
type Negation = `!${Exclude<EventName | Glob, '*'>}`;
/**
* The rest of the chain, as one hook receives it: made once per dispatch per
* hook, frozen; `next(e)` resolves to the downstream result.
*
* Each call runs the hooks below again; core is the last, and below it `next`
* rejects. Called with no argument it rejects, naming the hook. A hook that
* returns without calling it ends the chain; returning nothing is a failure.
*
* @template S what `next.is(pattern, e)` narrows `e` to, per event: the event's
* argument, or, under a matcher, that argument narrowed by it (MatchedHook)
* @template T the tool `e` names, when it names one: on `tool.call` it types
* the result (NextResultFor); an `e` without `tool` takes the line beneath
*/
export type Next<N extends EventName = EventName, E = Args<N>, O = NextResult<N>, S extends {
[K in N]?: unknown;
} = {
[K in N]: Args<K>;
}> = {
<T extends string>(e: E & ToolNamed<T>): Promise<NextResultFor<N, O, T>>;
(e: E): Promise<O>;
/**
* Continues this dispatch at a tier: `next(e)` with every link between
* this hook's own tier and that one skipped, by tier and narrowing only.
*
* A managed hook's: prepend may name append, builtin or core, append core;
* it never skips a tier with more authority, so no user hook skips the
* org's. A literal on the hook's own `next`; skipped links are traced.
*/
readonly to: {
<T extends string>(e: E & ToolNamed<T>, tier: TargetTier): Promise<NextResultFor<N, O, T>>;
(e: E, tier: TargetTier): Promise<O>;
};
/**
* Aborts when the call this dispatch belongs to is abandoned: the user
* interrupted, a hook above settled first, or this hook ran out of budget.
*
* Anything the hook started (timers, requests) should stop on it. It is an
* AbortSignal of the plugin's own environment, driven by the chain's.
*/
readonly signal: AbortSignal;
/**
* Whether this dispatch's event is selected by `pattern` (a name, a glob,
* a negation), as a type predicate on `e`: `next.is("tool.call", e)`.
*
* Under a matcher the narrowing includes it. `pattern` names events this
* hook covers (PatternOver); a name outside them is a compile error.
*/
readonly is: <M extends PatternOver<N>>(pattern: M, e: unknown) => e is Frozen<S[Extract<N, Selected<M>>]>;
/**
* The name of this dispatch's event, as a value, for a glob hook to log or
* switch on.
*/
readonly event: N;
/**
* Who raised this dispatch: the calling plugin's name and the tier it sits
* in (Origin); the engine reads `{ plugin: "engine", tier: "core" }`.
*
* Set by the host alone, from the environment the call came from (its own
* MessagePort) and that plugin's seat; nothing a plugin writes reaches it.
* Every hook of one dispatch sees the same origin, and `next.to` keeps it.
*
* @example
* return next.origin.tier === "prepend" ? next.to(e, "append") : next(e)
*/
readonly origin: Origin;
/**
* What settled beneath this hook on its latest `next()` call, the one
* started last: an entry per link beneath, nearest first, the engine's last.
*
* Empty before `next` is called; filled even when `next` rejected; a link
* still running joins in place later, nothing listed leaves; it ends short
* of the engine at a link that answered its last call itself. Data, frozen.
*/
readonly trace: readonly TraceEntry<N, E, O>[];
};
/**
* What `next(e)` resolves to for event `N`: the event's result, except at
* `engine.create`, where the steps beneath return `$` as built so far.
*
* A withheld noun is on that `$` as a stub, so the built table is typed
* whole where what a hook returns (EngineCreateResult) is partial.
*/
export type NextResult<N extends EventName> = N extends 'engine.create' ? EngineInterfaceBuilt : EventResult<N>;
/**
* What `next(e)` resolves to once `e.tool` is the literal `T`: on `tool.call`
* the result typed for that tool; on every other event, `O` as declared.
*
* `result` is Bash's record after `e.tool === "Bash"`; an un-narrowed `e`
* names every tool, and `result` stays `unknown`.
*/
export type NextResultFor<N extends EventName, O, T extends string> = [
N
] extends ['tool.call'] ? ToolCallResult<T> : O;
/**
* The argument of a call on `$` that takes nothing (`$.session.cwd()`): an
* object with no keys.
*/
type NoArgs = Record<never, never>;
/**
* The events whose argument is exactly NoArgs (`session.cwd`, a declared
* plugin noun's `() => ...`); their overloads come last (LateOverload).
*/
type NoArgsEvent = {
[N in EventName]: Args<N> extends NoArgs ? NoArgs extends Args<N> ? N : never : never;
}[EventName];
/**
* What an `engine.create` hook receives as `$`: nothing. Every property
* reads as `never`, so `$.model` inside the hook is a compile error.
*/
export type NoEngineInterface = {
readonly [noun: string]: never;
};
/**
* Array type `V`, of element `Item`, once some element of it is known to
* match: a tuple of at least one `Item`, readonly when `V` is.
*
* So `e` still passes wherever the declared array is taken; a `V` that is
* already a non-empty tuple is kept as it is.
*/
type NonEmpty<V, Item> = V extends readonly [unknown, ...unknown[]] ? V : V extends Item[] ? [Item, ...Item[]] : readonly [Item, ...Item[]];
type NotificationHookInput = BaseHookInput & {
hook_event_name: 'Notification';
message: string;
title?: string;
notification_type: string;
};
/**
* The declared plugin nouns' methods as event rows (NounEventRow), one per
* `<noun>.<method>` that is a function; a member that is not is no event.
*/
type NounEvent = {
[K in PluginNoun]: {
[M in keyof EngineInterface[K] & string]: EngineInterface[K][M] extends (...args: infer Parameters) => infer Result ? NounEventRow<`${K}.${M}`, Parameters extends readonly [] ? NoArgs : Parameters[0], Awaited<Result>> : never;
}[keyof EngineInterface[K] & string];
}[PluginNoun];
/**
* The name of a declared plugin noun's event (`voice.speak`).
*/
type NounEventName = keyof NounEventOf & string;
/**
* The events of the plugin nouns declared on EngineInterface, by name: the
* argument of each `<noun>.<method>`. Empty until a plugin declares a noun.
*
* @example
* declare module "claude-code" { interface EngineInterface { voice: Voice } }
*/
export type NounEventOf = {
[E in NounEvent as E['name']]: E['args'];
};
/**
* The result of a declared plugin noun's event as its hooks see it:
* `{ value }` (the method's answer) or `{ deny }`.
*/
type NounEventResult<N extends NounEventName> = ValueOrDeny<NounValueOf[N]>;
/**
* One method of a declared plugin noun as an event row: its event's name,
* argument (the method's first parameter) and value (its awaited result).
*/
type NounEventRow<Name extends string, Args, Value> = {
name: Name;
args: Args;
value: Value;
};
/**
* What each declared plugin noun's method answers (the `value` of its
* event's result), by event name.
*/
type NounValueOf = {
[E in NounEvent as E['name']]: E['value'];
};
/**
* Registers `hook` on the events `pattern` selects: one by name, every one
* under a namespace (`classic.*`), all (`*`), or all but some (`!tool.*`).
*
* One function stands on every selected event (`next.event` says which),
* under a matcher for the inputs it matches; a plugin's registrations nest
* in order, first outermost; a repeat throws. Returns the Registration.
*/
export type On = {
<P extends Pattern>(pattern: P, hook: NoInfer<HookFor<P>>): Registration<HookFor<P>>;
<P extends Pattern, const M extends Matcher<Args<MatchedNames<P>>>>(pattern: P, matcher: M, hook: NoInfer<MatchedHook<P, M>>): Registration<MatchedHook<P, M>>;
};
/**
* The keys a variant with a string index signature (an MCP tool's input)
* takes beyond its own: another variant's key as typed there; others free.
*
* So a misspelt value for a key some variant declares (`command: 5`) is
* refused on every variant, not admitted by the open one.
*/
type OpenMatcher<I, All> = {
readonly [K in Exclude<MatcherKeys<All>, KnownKeys<I>>]?: MatcherValue<MatcherValueOf<All, K>>;
} & Readonly<Record<string, unknown>>;
/**
* The name of a call on `$` the host serves, as an event.
*/
export type OpEventName = keyof OpEventOf;
/**
* The calls on `$` the host serves, as events: `e` is the call's argument as
* it crosses to the host, and every one is hookable by name and by `on("*")`.
*
* A hook above the caller passes it on, rewrites it, refuses it with
* `{ deny }` or answers with `{ value }`; core is the host's implementation.
* The calling hook alone is skipped, and `next.origin` names the caller.
*/
export type OpEventOf = {
/**
* The argument of `$.model.complete(request)`.
*/
'model.complete': ModelCompleteRequest;
/**
* The argument of `$.model.classify(text, labels, options)`.
*/
'model.classify': {
text: string;
labels: readonly string[];
options?: ClassifyOptions;
};
/**
* The argument of `$.model.fork(request)`.
*/
'model.fork': ModelForkRequest;
/**
* The clip and how to play it (`shouldLoop`, `gain`); the signal does not
* cross.
*/
'audio.play': {
clip: AudioClip;
shouldLoop: boolean;
gain?: number;
};
/**
* The argument of `$.audio.speak(text, { voice })`.
*/
'audio.speak': SpeakRequest;
/**
* The argument of `$.mcp.call(server, tool, args)`.
*/
'mcp.call': {
server: string;
tool: string;
args: Record<string, unknown>;
};
/**
* The argument of `$.session.cwd()`.
*/
'session.cwd': NoArgs;
/**
* The argument of `$.session.model()`.
*/
'session.model': NoArgs;
/**
* The argument of `$.session.turns()`.
*/
'session.turns': NoArgs;
/**
* The argument of `$.session.id()`.
*/
'session.id': NoArgs;
/**
* The argument of `$.session.messages()`.
*/
'session.messages': NoArgs;
/**
* The argument of `$.session.repo()`.
*/
'session.repo': NoArgs;
/**
* The argument of `$.session.surface()`.
*
* @deprecated with `$.session.surface()`; hook `session.surfaces`
*/
'session.surface': NoArgs;
/**
* The argument of `$.session.surfaces()`.
*/
'session.surfaces': NoArgs;
/**
* The argument of `$.session.authorize()`.
*/
'session.authorize': NoArgs;
/**
* The argument of `$.session.usage({ breakdown, columns })`.
*/
'session.usage': SessionUsageArgs;
/**
* The argument of `$.turn.abort({ turnId })`.
*/
'turn.abort': {
turnId: string;
};
/**
* The argument of `$.tool.list()`.
*/
'tool.list': NoArgs;
/**
* The argument of `$.tool.register(spec)`.
*/
'tool.register': Required<ToolSpec>;
/**
* The argument of `$.command.list()`.
*/
'command.list': NoArgs;
/**
* The argument of `$.command.register(spec)`.
*/
'command.register': CommandSpec;
/**
* The argument of `$.config.list()`.
*/
'config.list': NoArgs;
/**
* The argument of `$.agent.list()`.
*/
'agent.list': NoArgs;
/**
* The argument of `$.ui.toast(text, { timeoutMs })`.
*/
'ui.toast': {
text: string;
timeoutMs?: number;
};
/**
* The argument of `$.ui.status(text)`; `text` undefined clears the line.
*/
'ui.status': {
text: string | undefined;
};
/**
* The argument of `$.ui.log(text)`.
*/
'ui.log': {
text: string;
};
/**
* The argument of `$.ui.notice(tool_use_id, text)`.
*/
'ui.notice': {
tool_use_id: string;
text: string | undefined;
};
/**
* The argument of `$.ui.invalidate(event)`.
*/
'ui.invalidate': {
event: InvalidatableEventName;
};
/**
* The argument of `$.ui.open({ id, title, focus })`; a hook above the
* opener may retitle it or refuse it with `{ deny }`, never rename it.
*/
'ui.open': PaneOpenArgs;
/**
* The argument of `$.ui.close({ id })` with `origin` `plugin`; the engine
* raises it too, for the person (`person`) and an unload (`unload`).
*/
'ui.close': PaneCloseInput;
/**
* The argument of `$.ui.blit({ requestId, key, cells })`; a hook above
* the painter may repaint the cells with `next`, or refuse with `{ deny }`.
*/
'ui.blit': UiBlitArgs;
/**
* The argument of `$.fs.read(path)`.
*/
'fs.read': {
path: string;
};
/**
* The argument of `$.fs.write(path, text)`.
*/
'fs.write': {
path: string;
text: string;
};
/**
* The argument of `$.fs.list(path)`.
*/
'fs.list': {
path: string;
};
/**
* The argument of `$.fs.exists(path)`.
*/
'fs.exists': {
path: string;
};
/**
* The argument of `$.fs.stat(path)`.
*/
'fs.stat': {
path: string;
};
/**
* The argument of `$.fs.ancestors({ names, of })`.
*/
'fs.ancestors': FsAncestorsRequest;
/**
* The argument of `$.store.get(key)`.
*/
'store.get': {
key: string;
};
/**
* The argument of `$.store.set(key, value)`.
*/
'store.set': {
key: string;
value: unknown;
};
/**
* The argument of `$.store.delete(key)`.
*/
'store.delete': {
key: string;
};
/**
* The argument of `$.store.keys()`.
*/
'store.keys': NoArgs;
/**
* The argument of `$.clock.now()`.
*/
'clock.now': NoArgs;
/**
* The argument of `$.clock.sleep(ms, { signal })`; the signal does not
* cross, it aborts the dispatch.
*/
'clock.sleep': ClockWait;
/**
* The argument of `$.clock.after(ms, fn)`: the wait before `fn`, which
* stays in the plugin's environment and runs once the dispatch resolves.
*/
'clock.after': ClockWait;
/**
* The argument of `$.clock.every(ms, fn)`, dispatched once per period:
* `fn` runs each time a dispatch resolves, and the next period is asked.
*/
'clock.every': ClockWait;
/**
* The argument of `$.http.fetch(url, init)`.
*/
'http.fetch': {
url: string;
init?: HttpInit;
};
/**
* The argument of `$.process.run(argv, init)`.
*/
'process.run': {
argv: readonly string[];
init?: ProcessRunInit;
};
/**
* The argument of `$.settings.read({ source })`.
*/
'settings.read': SettingsReadArgs;
/**
* The argument of `$.env.get(name)`; `name` is identity, pinned.
*/
'env.get': {
name: string;
};
/**
* The argument of `$.env.set(name, value)`; `name` is identity, pinned,
* and no `value` unsets.
*/
'env.set': {
name: string;
value?: string;
};
};
/**
* The result of a call on `$` as its event's hooks see it: `{ value }` (the
* call's answer) or `{ deny }`.
*/
export type OpEventResult<N extends OpEventName = OpEventName> = ValueOrDeny<OpValueOf[N]>;
/**
* What each call on `$` answers (the `value` of its event's result), by event
* name.
*/
export type OpValueOf = {
'model.complete': string;
'model.classify': string | undefined;
'model.fork': ModelForkResult | null;
'audio.play': void;
'audio.speak': SpeakResult;
'mcp.call': McpToolResult;
'session.cwd': string;
'session.model': string;
'session.turns': number;
'session.id': string;
'session.messages': SessionMessage[];
'session.repo': SessionRepo | null;
'session.surface': RenderSurface | null;
'session.surfaces': readonly RenderSurface[];
/**
* The credential handle, or null where the build or the provider has no
* first-party credential to hold.
*/
'session.authorize': SessionAuthorization;
'session.usage': SessionUsage;
'turn.abort': void;
'tool.list': ToolInfo[];
'tool.register': {
tool: string;
};
'command.list': CommandInfo[];
'command.register': {
command: string;
};
'config.list': ConfigRow[];
'agent.list': AgentInfo[];
'ui.toast': void;
'ui.status': void;
'ui.log': void;
'ui.notice': void;
'ui.invalidate': void;
'ui.open': void;
'ui.close': void;
'ui.blit': UiBlitResult;
'fs.read': string;
'fs.write': void;
'fs.list': FsEntry[];
'fs.exists': boolean;
'fs.stat': FsStat;
'fs.ancestors': readonly FsAncestor[];
'store.get': unknown;
'store.set': void;
'store.delete': void;
'store.keys': string[];
/**
* Milliseconds since the epoch.
*/
'clock.now': number;
'clock.sleep': void;
'clock.after': void;
'clock.every': void;
'http.fetch': HttpResponse;
'process.run': ProcessRunResult;
'settings.read': Settings;
'env.get': string | undefined;
'env.set': void;
};
/**
* One call signature per event in `Names`, intersected, the ambiguous ones
* (LateOverload) after the rest: `next` for a hook covering several events.
*
* An empty group contributes nothing (Overloads<never> is unknown).
*/
type OrderedOverloads<Names extends EventName> = Overloads<Exclude<Names, LateOverload>> & Overloads<Extract<Names, 'classic.PreToolUse'>> & Overloads<Extract<Names, 'turn.abort'>> & Overloads<Extract<Names, NoArgsEvent>>;
/**
* Who raised a dispatch, as `next.origin` holds it: the calling plugin's
* name and the tier it sits in; the engine reads `engine` in `core`.
*
* The same pair a `next.trace` entry names its link by, and an event's
* `provider` its subject's definer by. Set by the host from where the call
* came from and where that plugin was seated; nothing a plugin writes.
*/
export type Origin = {
/**
* Whose hook made the `$` call, by name; `"engine"` for a call site,
* `"client"` for a `Client` surface module's `ui.message` post.
*/
readonly plugin: string;
/**
* Where that plugin sits among the chain's tiers (Tier); `"core"` for the
* engine, the owning plugin's for a `client` post.
*/
readonly tier: Tier;
};
/**
* One call signature per event in `Names`, intersected into an overload set.
*/
type Overloads<Names extends EventName> = UnionToIntersection<{
[N in Names]: (e: Args<N>) => Promise<NextResult<N>>;
}[Names]>;
/**
* The argument of `$.ui.close`: the pane to close (`{ id }`). `origin` is
* the engine's to set: a plugin's call reads `plugin` at the hooks.
*/
export type PaneCloseArgs = Omit<PaneCloseInput, 'origin'>;
/**
* The input of `ui.close`: the pane closing and why (PaneCloseOrigin).
* Closing an id that is not open does nothing.
*/
export type PaneCloseInput = {
/**
* What `$.ui.open` named the pane; pinned: `next(e)` passes it on.
*/
id: string;
/**
* Who closes it, set by the engine: a hook that answers without `next`
* keeps the pane open on `plugin` and `person`, never on `unload`.
*/
origin: PaneCloseOrigin;
};
/**
* Why a pane closes, as the engine stamped it at `ui.close`.
*
* `unload` drops a pane nothing draws any more (its plugin unloaded, or its
* drawing threw): it is gone before the hooks hear of it, and its opener's
* hooks do not run. `next(e)` passes the origin on as received; none sets it.
*/
export type PaneCloseOrigin = {
/**
* `plugin`, a plugin's `$.ui.close`; `person`, the person's close mark or
* close key; `unload`, the engine's own.
*/
kind: 'plugin' | 'person' | 'unload';
};
/**
* The argument of `$.ui.open`: which pane, its title, whether it asks the
* person's keyboard, its dialog manners, and the rows it wants inline.
*
* An open answering the person's input (a command or prompt they entered, a
* press) is placed at any width; one the plugin makes on its own waits
* undrawn below 144 terminal columns, 110 once they asked for that id.
*/
export type PaneOpenArgs = {
/**
* Names the pane: 1-64 of letters, digits, `_` and `-`. One pane per id:
* opening an open id delivers the new title, never a second instance.
*
* Pinned at the hooks: `next(e)` passes it on; the title and focus rewrite.
*/
id: string;
/**
* The pane's tab while more than one pane is open (with one, no title is
* drawn), and the `title` its hook sees; the id when omitted.
*/
title?: string;
/**
* A request, not a grant: the surface focuses (and raises) the pane only
* while the prompt has the keys over an empty composer.
*
* An element of the band or a pane the person holds, text in the
* composer, a dialog or a survey each refuse it: the pane opens without
* the keyboard.
*/
focus?: true;
/**
* While the pane holds the keyboard, the key that hands it back (Escape)
* also closes it as the person's close does: `ui.close`, origin `person`.
*
* A hook may refuse that close and keep it open. Left out, Escape returns
* the keys to the prompt and the pane stays. Each open sets it anew, as it
* sets the title.
*/
closeOnEscape?: true;
/**
* While the pane is on screen the surface holds its transient toasts (the
* notification line under the prompt) and shows them once it closes.
*
* As it does behind the engine's own side panel; pinned warnings still
* show. Left out, toasts show as they come. Each open sets it anew.
*/
holdToasts?: true;
/**
* The body rows the pane's content wants while seated inline above the
* prompt: it opens that tall, up to what the layout spares, not a third.
*
* A request, not a grant: a size the person dragged or keyed the block
* to wins, this session's or a kept one, and the dock ignores it. A
* positive whole number; left out, a third. Each open sets it anew.
*/
rows?: number;
};
/**
* What `on(pattern, hook)` and `next.is(pattern, e)` take: an event's name,
* a glob (`*`, `classic.*`), or a negation of either (`!tool.describe`).
*/
export type Pattern = EventName | Glob | Negation;
/**
* The patterns `next.is` takes in a hook covering the events `N`: their
* names, `*`, a glob over one of their namespaces, or a negation.
*
* A name none of them has is a compile error, as is a glob over a namespace
* none is under; a negation that selects none of them narrows `e` to never.
*/
type PatternOver<N extends EventName> = N | '*' | `${Namespace<N>}.*` | Negation;
type PermissionBehavior = 'allow' | 'deny' | 'ask';
type PermissionDeniedHookInput = BaseHookInput & {
hook_event_name: 'PermissionDenied';
tool_name: string;
tool_input: unknown;
tool_use_id: string;
reason: string;
};
/**
* Permission mode for controlling how tool executions are handled. 'default' - Standard behavior, prompts for dangerous operations. 'acceptEdits' - Auto-accept file edit operations. 'bypassPermissions' - Bypass all permission checks (requires allowDangerouslySkipPermissions). 'plan' - Planning mode, no actual tool execution. 'dontAsk' - Don't prompt for permissions, deny if not pre-approved. 'auto' - Use a model classifier to approve/deny permission prompts.
*/
type PermissionMode = 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan' | 'dontAsk' | 'auto';
/**
* A `classic.PermissionRequest` answer's `decision`, as the classic hook's
* `hookSpecificOutput.decision`: allow (with a rewrite or rules) or deny.
*/
export type PermissionRequestDecision = {
behavior: 'allow';
updatedInput?: Record<string, unknown>;
updatedPermissions?: PermissionUpdates;
} | {
behavior: 'deny';
message?: string;
interrupt?: true;
};
type PermissionRequestHookInput = BaseHookInput & {
hook_event_name: 'PermissionRequest';
tool_name: string;
tool_input: unknown;
permission_suggestions?: PermissionUpdate[];
};
type PermissionRuleValue = {
toolName: string;
ruleContent?: string;
};
type PermissionUpdate = {
type: 'addRules';
rules: PermissionRuleValue[];
behavior: PermissionBehavior;
destination: PermissionUpdateDestination;
} | {
type: 'replaceRules';
rules: PermissionRuleValue[];
behavior: PermissionBehavior;
destination: PermissionUpdateDestination;
} | {
type: 'removeRules';
rules: PermissionRuleValue[];
behavior: PermissionBehavior;
destination: PermissionUpdateDestination;
} | {
type: 'setMode';
mode: PermissionMode;
destination: PermissionUpdateDestination;
} | {
type: 'addDirectories';
directories: string[];
destination: PermissionUpdateDestination;
} | {
type: 'removeDirectories';
directories: string[];
destination: PermissionUpdateDestination;
};
type PermissionUpdateDestination = 'userSettings' | 'projectSettings' | 'localSettings' | 'session' | 'cliArg';
/**
* The permission rules a PermissionRequest allow may add: the shape of the
* request's own `permission_suggestions` (the SDK's PermissionUpdate list).
*/
type PermissionUpdates = NonNullable<ClassicHookInputs['PermissionRequest']['permission_suggestions']>;
/**
* How `$.audio.play` plays a clip: looped until `signal` aborts, or once.
*
* A loop needs the signal that ends it; a single play takes one as an option.
*/
export type PlayOptions = {
/**
* Repeat the clip until `signal` aborts (the promise then resolves).
*/
shouldLoop: true;
/**
* Linear gain, from 0 to 4; default 1.
*/
gain?: number;
/**
* Stops the clip: playback ends at once and the promise resolves.
*/
signal: AbortSignal;
} | {
/**
* Play once.
*/
shouldLoop?: false;
/**
* Linear gain, from 0 to 4; default 1.
*/
gain?: number;
/**
* Stops the clip early, as above.
*/
signal?: AbortSignal;
};
/**
* The nouns a plugin declared on `$` by merging into EngineInterface; never
* one the engine's own events are under (`tool`, `session`, `ui`).
*/
type PluginNoun = Exclude<keyof EngineInterface & string, keyof CoreEngineInterface | Namespace<CoreEventName>>;
/**
* A plugin's options as `register(on, options)` receives them: the values of
* the fields its manifest's `userConfig` declares, defaults filled in.
*
* Stored in settings.json `pluginConfigs[<plugin>].options` (sensitive ones
* in secure storage), validated against the declared `type` before the module
* loads; a required field with no value fails the load, naming the field. A
* string field that declares `options` holds one of them: `/config` draws it
* as a picker over them, and a stored value outside them counts as unset, so
* its default applies. A `--plugin-dir` plugin's key is its plugin.json
* `<name>` (or `<name>@inline`).
*/
export type PluginOptions = Readonly<Record<string, string | number | boolean | readonly string[]>>;
/**
* The input of `plugin.register`: one hooks module the engine is about to
* load, read off its manifest and its scanned source. Every field is pinned.
*
* `tier` and `uses` are the host's reading of the module, what a gate holds
* it to; `name`, `root`, `version` and `provenance` are its own word (its
* manifest, its place), so a rule keyed on them is one a rename walks past.
*/
export type PluginRegisterInput = {
/**
* The plugin's name, as its own plugin.json declares it.
*/
name: string;
/**
* Where its hooks would stand among the chain's tiers (Tier); never
* `core`, the engine's own.
*/
tier: Exclude<Tier, 'core'>;
/**
* The plugin's directory (the one holding plugin.json), absolute.
*/
root: string;
/**
* Its manifest's `version`, when it states one.
*/
version?: string;
/**
* Where the plugin came from, as the loader keys it: `<name>@<marketplace>`
* installed, `<name>@inline` by `--plugin-dir`, `<name>@builtin` bundled.
*/
provenance: string;
/**
* What the module hooks and calls, as scanned (PluginRegisterUses).
*/
uses: PluginRegisterUses;
};
/**
* What a `plugin.register` hook returns and what `next(e)` resolves to:
* `{ allow: true }` from core, or `{ refuse: reason }`.
*/
export type PluginRegisterResult = {
/**
* The module loads: its `engine.create` step runs and its hooks join.
*/
allow: true;
refuse?: undefined;
} | {
/**
* The module does not load: no step, no hooks, no tools or commands;
* the transcript names the plugin that refused and this reason.
*/
refuse: string;
allow?: undefined;
};
/**
* What a hooks module uses, as the host scanned its source before loading it:
* the same lists `claude plugin validate` prints and the host's rule reads.
*
* Exact, since a module that spells `on`, `$` or `$.env` other than literally
* does not load.
*/
export type PluginRegisterUses = {
/**
* The patterns its `on(...)` registrations name, as written (`tool.call`,
* `*`, `classic.*`, `!tool.describe`), in registration order, each once.
*/
events: readonly string[];
/**
* What it calls on `$`, spelled `noun.method` (`fs.write`, `http.fetch`),
* sorted, each once.
*/
calls: readonly string[];
/**
* The environment variables its `$.env.get` and `$.env.set` calls name;
* absent when it calls neither.
*/
env?: {
/**
* The names its `$.env.get` calls spell, sorted, each once.
*/
reads: readonly string[];
/**
* The names its `$.env.set` calls spell, sorted, each once.
*/
writes: readonly string[];
};
};
/**
* Whose element: the plugin whose hook drew it, stamped by the runtime as the
* tree leaves it; a Box's or Text's `group`, a Client's or Raster's own.
*
* A Button's `press` names its plugin the same way, beside its handle. Two
* plugins under one `hover.scope` string never share a group.
*/
type PluginStamp = {
plugin: string;
};
type PostCompactHookInput = BaseHookInput & {
hook_event_name: 'PostCompact';
trigger: 'manual' | 'auto';
/**
* The conversation summary produced by compaction
*/
compact_summary: string;
};
type PostModelSwitchHookInput = (BaseHookInput & {
hook_event_name: 'PostModelSwitch';
}) & {
/**
* Resolved model id the session was running before the switch
*/
from_model: string;
/**
* Resolved model id the session runs after the switch
*/
to_model: string;
/**
* What was asked for (alias such as "opus", a full id, or null for "default")
*/
requested_model: string | null;
/**
* command: /model <name>, the /config Model row, or enabling fast mode when that promotes the model; picker: an interactive model picker; sdk: headless set_model (SDK, Remote Control, IDE); auto: automatic fallback or other programmatic change; resume: model restored while resuming a session
*/
source: 'command' | 'picker' | 'sdk' | 'auto' | 'resume';
/**
* Prompt tokens the next request re-sends: the last main-thread response's input + cache_read + cache_creation + output tokens (0 before the first response; for a server-side tool loop, its last iteration's window, not the summed totals)
*/
context_tokens: number;
/**
* Whether the current model's prompt cache is likely still warm (a switch then forfeits it)
*/
prompt_cache_warm: boolean;
cache_ttl: '5m' | '1h';
/**
* Estimated cost of re-caching context_tokens on to_model at its cache-write rate - the managed modelPricing when set, otherwise list price; excludes the response
*/
estimated_cache_write_usd: number;
/**
* configured: priced at the managed modelPricing setting; catalog: list price; default: to_model unknown, the default tier was assumed
*/
pricing: 'configured' | 'catalog' | 'default';
};
/**
* Hook input for the PostToolBatch event. Fired once after every tool call in a batch has resolved, before the next model request. PostToolUse fires per-tool and may run concurrently for parallel tool calls; PostToolBatch fires exactly once with the full batch.
*/
type PostToolBatchHookInput = BaseHookInput & {
hook_event_name: 'PostToolBatch';
tool_calls: PostToolBatchToolCall[];
};
type PostToolBatchToolCall = {
tool_name: string;
tool_input: unknown;
tool_use_id: string;
tool_response?: unknown;
};
type PostToolUseFailureHookInput = BaseHookInput & {
hook_event_name: 'PostToolUseFailure';
tool_name: string;
tool_input: unknown;
tool_use_id: string;
error: string;
is_interrupt?: boolean;
/**
* Tool execution time in milliseconds. Excludes permission-prompt and hook time.
*/
duration_ms?: number;
};
type PostToolUseHookInput = BaseHookInput & {
hook_event_name: 'PostToolUse';
tool_name: string;
tool_input: unknown;
tool_response: unknown;
tool_use_id: string;
/**
* Tool execution time in milliseconds. Excludes permission-prompt and hook time.
*/
duration_ms?: number;
};
type PreCompactHookInput = BaseHookInput & {
hook_event_name: 'PreCompact';
trigger: 'manual' | 'auto';
custom_instructions: string | null;
};
type PreModelSwitchHookInput = (BaseHookInput & {
hook_event_name: 'PreModelSwitch';
}) & {
/**
* Resolved model id the session was running before the switch
*/
from_model: string;
/**
* Resolved model id the session runs after the switch
*/
to_model: string;
/**
* What was asked for (alias such as "opus", a full id, or null for "default")
*/
requested_model: string | null;
/**
* command: /model <name>, the /config Model row, or enabling fast mode when that promotes the model; picker: an interactive model picker; sdk: headless set_model (SDK, Remote Control, IDE)
*/
source: 'command' | 'picker' | 'sdk';
/**
* Prompt tokens the next request re-sends: the last main-thread response's input + cache_read + cache_creation + output tokens (0 before the first response; for a server-side tool loop, its last iteration's window, not the summed totals)
*/
context_tokens: number;
/**
* Whether the current model's prompt cache is likely still warm (a switch then forfeits it)
*/
prompt_cache_warm: boolean;
cache_ttl: '5m' | '1h';
/**
* Estimated cost of re-caching context_tokens on to_model at its cache-write rate - the managed modelPricing when set, otherwise list price; excludes the response
*/
estimated_cache_write_usd: number;
/**
* configured: priced at the managed modelPricing setting; catalog: list price; default: to_model unknown, the default tier was assumed
*/
pricing: 'configured' | 'catalog' | 'default';
};
/**
* The decision of a `classic.PreToolUse` result: `allow`, `ask`, `deny`, or
* none.
*/
export type PreToolUseDecision = {
/**
* Lets the call run without a permission prompt (the managed-settings
* hooks ran first; a deny from them ended the chain above).
*/
allow: true;
ask?: undefined;
deny?: undefined;
} | {
/**
* Asks the user before the call runs; the text is shown as the reason.
*/
ask: string;
allow?: undefined;
deny?: undefined;
} | {
/**
* Refuses the call; the model receives the text as the reason.
*/
deny: string;
allow?: undefined;
ask?: undefined;
} | {
allow?: undefined;
ask?: undefined;
deny?: undefined;
};
type PreToolUseHookInput = BaseHookInput & {
hook_event_name: 'PreToolUse';
tool_name: string;
tool_input: unknown;
tool_use_id: string;
};
/**
* What a `classic.PreToolUse` hook returns: one of `allow`, `ask`, `deny`,
* or none of them, which passes the call on to the normal permission flow.
*/
export type PreToolUseResult = PreToolUseDecision & {
/**
* Replaces the tool's arguments; validated against the tool's schema before
* the tool runs.
*/
updatedInput?: Record<string, unknown>;
/**
* Extra context handed to the model with the call, one entry per note.
*/
additionalContext?: string[];
};
/**
* Options of `$.process.run`.
*/
export type ProcessRunInit = {
/**
* The child's working directory, relative to the session's or absolute;
* absent, the session's working directory.
*/
cwd?: string;
/**
* Variables set over the host process's own environment.
*/
env?: Record<string, string>;
/**
* Text written to the child's standard input, then closed.
*/
stdin?: string;
/**
* How long the child may run before it is killed and the call rejects,
* in milliseconds; 30 seconds when absent, ten minutes at most.
*/
timeoutMs?: number;
};
/**
* What `$.process.run` resolves with once the child has exited.
*/
export type ProcessRunResult = {
/**
* The child's exit status; a child ended by a signal reads as 1.
*/
exitCode: number;
/**
* What the child wrote to standard output, as text, cut at the output
* limit.
*/
stdout: string;
/**
* What the child wrote to standard error, as text, cut at the output
* limit.
*/
stderr: string;
};
/**
* A pasted or attached non-text item of a prompt; its kind, never its bytes.
*/
export type PromptAttachment = {
/**
* The item's kind.
*/
type: 'image' | 'audio' | 'document';
/**
* The item's MIME type (`image/png`), when known.
*/
mediaType?: string;
/**
* The pasted file's name, when it had one.
*/
filename?: string;
};
/**
* One block of the context the first user message carries: a name the
* engine keys it by and the text under it.
*/
export type PromptContextBlock = {
/**
* The key the block renders under (`# name`): `claudeMd`, `userEmail`,
* `attachedProject`, `currentDate`, or a plugin's own.
*
* The field a matcher narrows on; unique among one context's blocks.
*/
name: string;
/**
* The block's text; `claudeMd`'s is the instruction files framed as the
* engine frames them, empty when it announces none.
*/
text: string;
};
/**
* The context blocks of a conversation's first user message, in the order
* the engine renders them: what `prompt.context` takes and answers alike.
*/
export type PromptContextBlocks = {
/**
* From core: `claudeMd` (when instruction files are loaded), `userEmail`,
* `attachedProject`, `currentDate`, each only when present.
*/
blocks: readonly PromptContextBlock[];
};
/**
* The input of `prompt.context`: the context blocks the engine prepends to
* a conversation's first user message, at the moment it computes them.
*/
export type PromptContextInput = PromptContextBlocks;
/**
* What a `prompt.context` hook returns: the blocks the conversation
* carries, in order; one left out is not sent.
*/
export type PromptContextResult = PromptContextBlocks;
/**
* `prompt.fill`'s input as a plugin's `$.prompt.fill(args)` takes it:
* `origin` is the engine's to set (the calling plugin's name).
*/
export type PromptFillArgs = Omit<PromptFillInput, 'origin'>;
/**
* The input of `prompt.fill` (prompt-fill/): a text about to be written into
* the prompt box as the person's draft, replacing what the box holds.
*/
export type PromptFillInput = {
/**
* What the box is to hold, cursor at its end; the person edits it or
* presses Enter. `next({ ...e, text })` writes another.
*/
text: string;
/**
* Who writes (PromptFillOrigin), set by the engine where the write
* starts. Pinned: `next(e)` passes it on as received.
*/
origin: PromptFillOrigin;
};
/**
* Who writes the prompt box at `prompt.fill`, as the engine stamps it where
* the write starts; a closed set a matcher narrows on.
*
* `next(e)` passes it on as received; no hook sets one.
*/
export type PromptFillOrigin = {
/**
* The engine writing the box on its own account; reserved for its own
* sites, none of which raises `prompt.fill` as shipped.
*/
kind: 'engine';
} | {
/**
* A plugin's `$.prompt.fill`.
*/
kind: 'plugin';
/**
* The filling plugin's name.
*/
name: string;
};
/**
* What a `prompt.fill` hook returns and what `next(e)` resolves to: whether
* the text went into the prompt box.
*/
export type PromptFillResult = {
/**
* True once the box holds the text; false where no box can take it (a
* dialog holds the keys, a headless session has none).
*
* A hook answering `{ isFilled: false }` without `next` keeps the text
* out.
*/
isFilled: boolean;
};
/**
* Where a `prompt.submit` submission came from, as the engine knows it at
* the site it was queued from; a closed set, never a text prefix.
*
* A hooks module reads `e.origin.kind` to tell the user's own Enter from a
* notification, a peer session, a schedule or another plugin. `next(e)`
* passes it on as received; an answer may leave it out; no hook sets one.
*/
export type PromptOrigin = {
/**
* The user's own gesture at the terminal, as the engine stamped it
* (never presumed from an unstamped command).
*
* Enter at the prompt, typed or queued, or a click on a transcript
* link; a channel the engine cannot attest (a same-user socket) is
* never stamped, and arrives as `unclassified`.
*/
kind: 'composer';
} | {
/**
* The user's message through the Remote Control bridge (a phone or
* web client).
*/
kind: 'bridge';
} | {
/**
* The SDK host's own turn (`claude -p`, the Agent SDK), not typed at
* a terminal.
*/
kind: 'sdk';
} | {
/**
* A background task's notification, dequeued when the session went
* idle or delivered into a running turn (`turnId` set).
*/
kind: 'task-notification';
} | {
/**
* A scheduled task, routine or /loop firing its stored prompt.
*/
kind: 'scheduled-trigger';
} | {
/**
* Another Claude session's message ("Another Claude session sent a
* message"), as a turn of its own or delivered into a running one.
*/
kind: 'peer';
} | {
/**
* Another session's SendMessage delivery, model-authored and framed
* as a notification.
*/
kind: 'peer-send-message';
} | {
/**
* A delivery a coordinating session composed for one of its threads.
*/
kind: 'projects-relay';
} | {
/**
* A message from a channel an MCP server relays (Slack, Telegram).
*/
kind: 'channel';
/**
* The channel server's name.
*/
server: string;
} | {
/**
* A coordinating session's hand-off to a worker session.
*/
kind: 'coordinator';
} | {
/**
* A background observer agent's report to the agent it observes.
*/
kind: 'observer';
} | {
/**
* An activity digest delivered to an observer agent.
*/
kind: 'observer-activity';
} | {
/**
* A programmatic follow-up to a user's UI action, user-initiated but
* not typed this turn.
*/
kind: 'auto-continuation';
} | {
/**
* A turn with no provenance the engine can name: one the ingress
* could not classify, or a command queued with no stamp at all.
*
* An idle notice or a delivery receipt the engine queued isMeta with
* no stamp is one too; the engine frames that shape as a non-user
* source.
*/
kind: 'unclassified';
} | {
/**
* The session's owner pinging it from Slack.
*/
kind: 'slack-ping';
} | {
/**
* A plugin's `$.prompt.submit`; the model reads the prompt under the
* plugin's name unless a hook leaves the origin out of its answer.
*/
kind: 'plugin';
/**
* The submitting plugin's name.
*/
name: string;
};
/**
* The input of `prompt.section`: one named section of the system prompt, at
* the moment the engine assembles it.
*/
export type PromptSectionInput = {
/**
* As the engine names the section (`env_info_simple`, `memory`, ...); the
* key a matcher narrows on.
*/
name: string;
/**
* The section's text as core computed it, or null when core omits it.
*/
text: string | null;
};
/**
* What a `prompt.section` hook returns: the text the prompt carries for that
* section, or null to leave it out.
*/
export type PromptSectionResult = {
text: string | null;
};
/**
* `prompt.submit`'s input as a plugin's call takes it: `origin`, `turnId`
* and `wait` are the engine's to set, `context` the hooks' to attach.
*
* `origin` is the calling plugin's name; `turnId` is the turn a prompt typed
* mid-turn ran over; `wait` is false, as a plugin's prompt runs once idle.
*/
export type PromptSubmitArgs = Omit<PromptSubmitInput, 'origin' | 'turnId' | 'wait' | 'context'>;
/**
* The input of `prompt.submit`: the prompt as typed, after the input became
* a user message and before it enters the session.
*/
export type PromptSubmitInput = {
/**
* The prompt's text as it will reach the model (pastes already expanded).
*/
text: string;
/**
* Present only when the submission carried images or other non-text items.
*/
attachments?: readonly PromptAttachment[];
/**
* What the model reads beside the prompt and the user never sees, each
* entry one block after the prompt as typed; absent as the engine raises it.
*
* A hook attaches on the way down: `next({ ...e, context: [...(e.context
* ?? []), mine] })`. It may not leave out an entry it received; the whole
* is capped at 32000 characters, no entry empty.
*/
context?: readonly string[];
/**
* The id of the model turn that was running when the prompt was submitted
* (`turn.start`'s `turnId`): typed over that turn, or delivered into it.
*
* A queued delivery (a peer session's message) reaches the model inside a
* running turn. Absent for a prompt submitted while the session was idle,
* and for a plugin's own (`$.prompt.submit`), which runs once it is idle.
*/
turnId?: string;
/**
* Whether the user asked the prompt to wait its turn (`chat:queueSubmit`,
* `ctrl+x enter` by default): true for that submission, false otherwise.
*
* The engine queues every prompt typed mid-turn either way; the flag is
* for hooks, so one that cancels the running turn on a plain Enter can
* leave a waiting prompt alone. False for a prompt a plugin submitted.
*/
wait: boolean;
/**
* Where the submission came from (PromptOrigin), set by the engine where
* it was queued: the user's Enter, a notification, a peer, a plugin.
*
* `next(e)` passes it on as received; no hook may set one.
*/
origin: PromptOrigin;
};
/**
* What a `prompt.submit` hook returns and what `next(e)` resolves to: the
* prompt that entered, `{ text, context?, origin? }`, or `{ drop: reason }`.
*
* `next(e)` resolves once the prompt entered the session and its turn
* started, or it was queued behind the running one; not when the turn ends,
* which is `turn.complete`. A hook answering without `next` enters nothing.
*/
export type PromptSubmitResult = {
/**
* The prompt that entered; from core, the text that arrived at the
* bottom. A rewrite passes it down, `next({ ...e, text })`.
*/
text: string;
/**
* What entered beside the prompt for the model, never shown the user:
* from core, the context that arrived (`e.context`).
*
* Each entry is one block after the prompt as typed. A hook attaches
* context on the way down; one put here after `next` resolved is not
* attached (the prompt had entered), and is logged.
*/
context?: readonly string[];
/**
* Where the prompt entered from: from core, `e.origin` as received;
* absent, the prompt is the user's own.
*
* A hook may put back the origin it received; it may not set another.
*/
origin?: PromptOrigin;
drop?: undefined;
} | {
/**
* The prompt did not enter: a hook's refusal, answered without `next`,
* or a settings hook's block beneath.
*
* The text is shown to the user as the reason.
*/
drop: string;
text?: undefined;
context?: undefined;
origin?: undefined;
};
/**
* `prompt.suggest`'s input as a plugin's `$.prompt.suggest(args)` takes it:
* `origin` is the engine's to set (the calling plugin's name).
*/
export type PromptSuggestArgs = Omit<PromptSuggestInput, 'origin'>;
/**
* The input of `prompt.suggest` (prompt-suggest/): a text about to be shown
* dim in the empty prompt box, for Tab (or the right arrow) to take.
*/
export type PromptSuggestInput = {
/**
* The proposed prompt: shown, not written; taking it puts it in the box
* for editing. `next({ ...e, text })` proposes another.
*/
text: string;
/**
* Who proposes (PromptSuggestOrigin), set by the engine where the
* proposal starts. Pinned: `next(e)` passes it on as received.
*/
origin: PromptSuggestOrigin;
};
/**
* Who proposes the text at `prompt.suggest`, as the engine stamps it where
* the proposal starts; a closed set a matcher narrows on.
*
* `next(e)` passes it on as received; no hook sets one.
*/
export type PromptSuggestOrigin = {
/**
* The engine's own guess at the person's next prompt, generated after
* a turn (the prompt-suggestion service).
*/
kind: 'suggestion';
} | {
/**
* A plugin's `$.prompt.suggest`.
*/
kind: 'plugin';
/**
* The proposing plugin's name.
*/
name: string;
};
/**
* What a `prompt.suggest` hook returns and what `next(e)` resolves to:
* whether the text is now the box's dim suggestion.
*/
export type PromptSuggestResult = {
/**
* True once the box has the suggestion to show, at once or as soon as a
* dialog gives the box back; false where it cannot show.
*
* It cannot while the box holds text, a turn runs, the text is blank, or
* the session is headless. A hook answering `{ isShown: false }` without
* `next` keeps it from showing.
*/
isShown: boolean;
};
/**
* The props of `Raster`, the terminal surface's cell-grid leaf: a fixed box
* of cells, each a glyph, a foreground and a background, packed in `cells`.
*
* A leaf: no children, `hover` or `onPress` yet; repainted in place by
* `$.ui.blit`. Terminal only for now (elsewhere a fragment); its palette
* paints 1024 distinct color pairs at once and the rest as their nearest.
*/
export type RasterProps = {
/**
* The element's address within the drawing: what `$.ui.blit` names to
* repaint it, unique among the Rasters of one tree.
*/
key: string;
/**
* How many terminal columns wide, 1 to 512; the site clips what its body
* cannot show.
*/
columns: number;
/**
* How many terminal rows tall, 1 to 256.
*/
rows: number;
/**
* Every cell, row-major: standard padded base64 of `columns * rows`
* little-endian u32 triplets `[codePoint, foreground, background]`.
*
* A code point is one printable width-1 BMP character (blocks, box drawing,
* braille too), or the tree is refused naming the cell's index; a color is
* `0x00RRGGBB`, or `0x01000000` (bit 24 alone) for the terminal's default.
*
* @example const words = Uint32Array.of(0x2588, 0xff8800, 0x01000000)
* const cells = new Uint8Array(words.buffer).toBase64() // one orange cell
*/
cells: string;
};
/**
* The hooks module's entry: `export function register(on, options)`. `on`
* registers hooks; `options` is the plugin's configuration (PluginOptions).
*
* The options are fixed for this activation: a change to them reloads the
* plugin and `register` runs again with the new object. Hooks close over it.
* Its return is dropped, a promise awaited: `on => on(...)` is a module.
*
* @example
* on("tool.call", ($, e, next) => e.tool === "Bash" ? { deny: "no" } : next(e))
*/
export type Register = (on: On, options: PluginOptions) => unknown;
/**
* What `on(...)` returns for a hook of type `F`: the registration, which
* takes one `.catch` (CatchHandler); without it a failed hook is absent.
*
* A second `.catch` on one registration throws, as does one after
* register() returned and one on `engine.create`, whose hook has no budget
* and whose failure is the load's.
*/
export type Registration<F> = {
/**
* Sets the handler run when the hook throws or overruns its budget; its
* answer within the grace stands as the hook's result for the dispatch.
*/
readonly catch: (handler: CatchHandler<F>) => void;
};
/**
* What an element takes as `children`, as JSX passes them: a node, a number
* (drawn as its string), a value the factory drops, or a list that may nest.
*
* `false`, `null` and `undefined` are dropped, so `{ok && <Text>hi</Text>}`
* and `{n > 0 ? <Text>{n}</Text> : null}` type; a mapped list beside a
* sibling nests. The element holds the flat, normalized list of RenderNode.
*/
export type RenderChildren = RenderNode | number | boolean | null | undefined | readonly RenderChildren[];
/**
* Everything `ui.render` can draw: one name per component that has a render
* site; a matcher narrows on it.
*
* The permission dialog is drawn by the engine alone, since its answer
* authorises an action; a plugin adds context with `$.ui.notice`. `Pane` is
* the one component whose instances a plugin opens (`$.ui.open`).
*/
export type RenderComponent = 'AskUserQuestion' | 'UserMessage' | 'AssistantMessage' | 'ToolUse' | 'ToolResult' | 'ToolGroup' | 'CommandOutput' | 'Spinner' | 'TurnDuration' | 'InfoNotice' | 'SessionMode' | 'PromptHint' | 'AbovePrompt' | 'Pane';
/**
* What a render hook returns, and what `next(e)` resolves to: a plain-data
* tree of elements (a Box or Text is a StyledElement), strings as children.
*
* Props are an allowlisted subset of Ink's Box/Text props (the ones
* ElementProps declares); a tree with any other prop fails validation as a
* whole and the engine's own component is drawn with the original props.
*/
export type RenderElement = StyledElement<'Box', BoxHoverProps> | StyledElement<'Text', TextHoverProps> | {
/**
* A button, on every surface: `[ label ]` on the terminal, a native
* button on a desktop; a press raises `ui.press` (`e.element` the key).
*
* Built by `<Button>` or the table's `t.Button`. The `onPress` closure
* stays in the plugin's own environment under `press.handle`; the host
* holds the handle for the lifetime of the drawing. A leaf: no children.
*/
type: 'Button';
props: {
/**
* The element's address: what `e.element` carries and what a matcher
* names (`{ element: "explain" }`).
*/
key: string;
/**
* The text drawn on the button.
*/
label: string;
/**
* One digit (`"1"`) or one lowercase letter (`"w"`) that presses it
* where the site honours one; anything else is refused.
*
* A bare digit in an empty composer presses, as a survey is answered;
* while one of the band's Buttons has the focus a digit or a letter
* presses on keydown, lowercased. Two on one hotkey: the later wins.
*/
hotkey?: string;
/**
* An engine keybinding action (`"app:cycleDiffBase"`) whose chord
* presses the Button from the prompt; an unknown name is refused.
*
* Chords, or a modified key Global or an active context binds, on
* the terminal while mounted, no dialog up, no engine handler of it
* mounted; a pane's over the band's over another's, the last drawn.
*/
action?: string;
/**
* Drawn without chrome: the hotkey in the accent color, a colon,
* then the label (`1: Yes`); without a `hotkey`, the label alone.
*
* The focus still inverts it. In JSX the label may be the one string
* child (`<Button hotkey="1" plain onPress={...}>Yes</Button>`); the
* key defaults to the label.
*/
plain?: true;
/**
* The label dim at rest, as `Text`'s `dimColor`, and at full strength
* under the pointer or the focus; absent draws as false.
*/
dimColor?: TextProps['dimColor'];
/**
* The site's ring starts on this element when the site takes the
* keyboard; the first drawn of several. Absent draws as before.
*/
autoFocus?: true;
};
/**
* Where the handler lives: the plugin whose hook drew the element, and
* the handle its environment keeps the `onPress` closure under.
*
* The runtime stamps the plugin as the tree leaves that hook.
*/
press: {
plugin: string;
handle: number;
};
/**
* Label style overrides (the Text set) the surface applies while the
* nearest keyed Box, or the group `scope` names, is hovered; plain data.
*/
hover?: TextHoverProps;
} | {
/**
* A one-line text field on every surface; a change and Enter raise
* `ui.input` (`e.element` the key, `e.kind` which, `e.value` the text).
*
* Built by `<Input>` or the table's `t.Input`. The `onInput` and
* `onSubmit` closures stay in the plugin's own environment under
* `press.handle`, held as a Button's is. A leaf: no children.
*/
type: 'Input';
props: {
/**
* The element's address: what `e.element` carries and what a matcher
* names (`{ element: "reply" }`).
*/
key: string;
/**
* Text drawn before the field.
*/
label?: string;
/**
* Text drawn dim in an empty field.
*/
placeholder?: string;
/**
* The text the field holds when drawn.
*/
value?: string;
/**
* What Enter does, drawn beside the field while it has focus.
*/
submitLabel?: string;
/**
* The site's ring starts on this element when the site takes the
* keyboard; the first drawn of several. Absent draws as before.
*/
autoFocus?: true;
};
/**
* Where the handlers live: the plugin whose hook drew the element, and
* the handle its environment keeps the closures under.
*
* The runtime stamps the plugin as the tree leaves that hook.
*/
press: {
plugin: string;
handle: number;
};
children?: undefined;
} | {
/**
* A one-of-several picker on every surface; a pick raises `ui.select`
* (`e.element` the key, `e.value` the option's value).
*
* Built by `<Select>` or the table's `t.Select`. The `onSelect` closure
* stays in the plugin's own environment under `press.handle`, held as
* a Button's is. A leaf: no children.
*/
type: 'Select';
props: {
/**
* The element's address: what `e.element` carries and what a matcher
* names (`{ element: "peer" }`).
*/
key: string;
/**
* Text drawn before the current value.
*/
label?: string;
/**
* What can be picked, in the order drawn: each a value and the text
* drawn for it.
*/
options: readonly SelectOption[];
/**
* Which option is selected when drawn.
*/
value?: string;
/**
* The site's ring starts on this element when the site takes the
* keyboard; the first drawn of several. Absent draws as before.
*/
autoFocus?: true;
};
/**
* Where the handler lives: the plugin whose hook drew the element, and
* the handle its environment keeps the closure under.
*
* The runtime stamps the plugin as the tree leaves that hook.
*/
press: {
plugin: string;
handle: number;
};
children?: undefined;
} | {
/**
* A hyperlink every surface draws: an OSC 8 span on the terminal (its
* text then the URL in dim where unsupported), an anchor on desktop.
*
* Inline: its children are the text, strings and inline elements;
* absent children the label, absent both the URL. `href` is `https:`
* (or `http://localhost`) and bounded, or the tree is refused.
*/
type: 'Link';
props: LinkProps;
children?: RenderNode[];
} | {
/**
* Source code every surface draws with the engine's highlighter, tokens
* coloured by language; under `format: 'diff'`, unified-diff hunks.
*
* A leaf: a dim gutter numbers the lines from `startLine`; a diff has
* both gutters, markers, add and remove backgrounds. `source` is
* bounded as a Text's string is, or the tree is refused.
*/
type: 'Code';
props: CodeProps;
children?: undefined;
} | {
/**
* A region one of the plugin's SURFACE MODULES, named by path, draws and
* handles input for on the drawing thread, without `$` (ClientModule).
*
* `Client` from the table. One instance per plugin, drawing and `key`
* lives while the node stays in the tree, and talks to the plugin's
* hooks through `ui.message`. The desktop carries it as data.
*/
type: 'Client';
props: ClientProps;
/**
* Whose surface module `props.module` names: the plugin whose hook
* drew the element, stamped by the runtime as the tree leaves it.
*/
client: {
plugin: string;
};
children?: undefined;
} | {
/**
* A vector drawing, the remote surfaces' alone: the SVG markup is the
* element's data, drawn in an isolated box, off the page.
*
* A leaf: hooks above wrap or replace it whole, nothing reaches inside;
* a press other plugins should see goes on an enclosing Button. On a
* surface whose table lacks it the tree is refused.
*/
type: 'Svg';
props: SvgProps;
children?: undefined;
} | {
/**
* A grid of terminal cells, the terminal surface's alone: each cell a
* glyph, a foreground and a background, packed in `props.cells`.
*
* A leaf, one node however many cells; hooks above wrap or replace it
* whole. A mounted one is repainted in place by its plugin's
* `$.ui.blit`. On a surface whose table lacks it the tree is refused.
*/
type: 'Raster';
props: RasterProps;
/**
* Whose Raster: the plugin whose hook drew the element, stamped by the
* runtime as the tree leaves it; the one plugin whose blit reaches it.
*/
raster: {
plugin: string;
};
children?: undefined;
} | {
/**
* The component core draws itself, with the props held under `ref`.
*/
type: 'engine';
/**
* Which drawing: the number core answered from `next(e)`, under which
* it holds the props it received; 0 draws the original props.
*/
ref: number;
};
/**
* The render event: `ui.render`, one event for every component that has a
* render site.
*/
export type RenderEventName = 'ui.render';
/**
* The input of `ui.render`: a union discriminated by `component`, one member
* per RenderComponent and per RenderSurface.
*/
export type RenderInput<C extends RenderComponent = RenderComponent, P extends RenderSurface = RenderSurface> = C extends RenderComponent ? P extends RenderSurface ? RenderInputOf<C, P> : never : never;
/**
* One `ui.render` input, for a component narrowed to one surface.
*/
export type RenderInputOf<C extends RenderComponent, P extends RenderSurface> = {
/**
* Where the tree will be drawn; one literal per member, so
* `if (e.surface === "terminal")` narrows `e` and `$.ui.resolve(e)`.
*
* Over the wire it is what the client declared, a rendering fact and not a
* trust signal: do not key policy on it.
*/
surface: P;
/**
* Which component this instance is; the key a matcher narrows on.
*/
component: C;
/**
* The instance: the tool_use_id for a dialog or tool row, the message id
* for a message, the agent id for a spinner.
*
* Two drawings of one component are two instances.
*/
requestId: string;
/**
* The size of what the surface draws into, in character cells; absent where
* no surface has measured. Part of the envelope: a rewrite keeps it.
*
* On the terminal, the interactive screen's size, where a change of width
* re-draws every hooked site once the resize settles (a hook that sized its
* tree to `columns` runs again); on a remote surface, what it reported.
*/
viewport?: RenderViewport;
/**
* The component's plain-data props.
*/
props: RenderPropsOf[C];
};
/**
* A node of a render tree: an element, or a string (text).
*/
export type RenderNode = RenderElement | string;
/**
* The plain-data props of each renderable component, as `ui.render` sees
* them under `e.props`; a hook rewrites them with `next({ ...e, props })`.
*
* A rewrite is validated by the component and an invalid one draws the
* original. This table is the plugin-facing render contract: the terminal
* and the Code session renderer draw these components from these props.
*/
export type RenderPropsOf = {
/**
* The dialog the AskUserQuestion tool opens.
*/
AskUserQuestion: {
/**
* The name of the tool whose call opened the dialog (`AskUserQuestion`).
*/
tool: string;
/**
* The tool's `questions` input, as the dialog will draw them; a rewrite
* must still fit the tool's schema or the original is drawn.
*/
questions: unknown[];
/**
* The call's `metadata.source` (who asked) when the model gave one.
* Analytics only; never drawn.
*/
metadataSource?: string;
};
/**
* The user's own prompt in the transcript (the `> ...` row); a rewrite is
* drawn there and nowhere else (the stored message is untouched).
*/
UserMessage: {
/**
* The prompt's text, as the row draws it.
*/
text: string;
/**
* Where the stored message came from, as `prompt.submit` named it
* (PromptOrigin): the composer's, a peer's, a notification's, a plugin's.
*
* Read-only: a rewrite carries it on as received; one that changes or
* drops it is refused and the engine draws its own row.
*/
origin: PromptOrigin;
};
/**
* One text block of an assistant reply in the transcript; a rewrite
* changes the drawing and leaves the stored message alone (ctrl+o).
*/
AssistantMessage: {
/**
* The block's text, markdown, as the transcript will draw it.
*/
text: string;
/**
* True on the block that draws the bullet opening a reply.
*/
isFirstOfReply: boolean;
};
/**
* A tool call's row in the transcript (`Bash(ls -la)` and its result); the
* call was decided by `tool.call`, so a rewrite here changes the row alone.
*/
ToolUse: {
/**
* The id `tool.call` carried for this call (`e.tool_use_id` there); the
* same value as the row's `requestId`, where it is looked for. Read-only.
*/
tool_use_id: string;
/**
* Which one the row draws (`Bash`, `Read`, a plugin's tool), as
* `tool.call` named it.
*/
tool: string;
/**
* The call's input, as the model sent it.
*/
input: unknown;
/**
* True while the call is still running.
*/
isRunning: boolean;
/**
* True when the call ended in an error (a refusal at the dialog is one).
*/
isErrored: boolean;
/**
* True when an abort ended the call: the user's Esc or a plugin's
* `$.turn.abort` cut it while it ran, or dropped it before it ran.
*
* The row draws `Interrupted` for it, as the transcript marker does.
*/
isInterrupted: boolean;
/**
* The stored result once the call has resolved (`{ stdout, stderr, ... }`
* for Bash: `BuiltinToolResults[tool]`); undefined while it runs.
*
* For a call that errored, was refused or an abort cut, it is the text
* the model read (an `isInterrupted` call: the abort's own). An expanded
* group's rows draw it inline; a standalone row's is its own `ToolResult`.
*/
output?: unknown;
};
/**
* The result block drawn under a standalone tool row in the transcript,
* which the tool's own result renderer draws from `output`.
*
* A rewrite of `output` is checked against the tool's output schema (one
* that does not fit draws nothing; one the renderer cannot read hits the
* row's error boundary). The stored result is untouched.
*/
ToolResult: {
/**
* The id `tool.call` carried for the call this result belongs to
* (`e.tool_use_id` there); the same value as `requestId`. Read-only.
*/
tool_use_id: string;
/**
* Which one the result belongs to (`Bash`, `Read`, a plugin's tool).
* Read-only.
*/
tool: string;
/**
* The tool's own result object (`{ stdout, stderr, interrupted, ... }` for
* Bash), the same one `ToolUse.output` carries; a rewrite is drawn.
*
* A built-in tool's is `BuiltinToolResults[tool]`, the record
* `tool.call` resolved as `result`.
*/
output: unknown;
/**
* True when the call ended in an error, which draws the error text and not
* `output`. Read-only.
*/
isErrored: boolean;
};
/**
* A run of tool calls the transcript folds into one count line (`Read 3
* files, ran 2 shell commands`): reads, searches, listings.
*
* A hook that sets `isExpanded` unfolds the group where it is, and each row
* it unfolds into is a `ToolUse` drawing a `ToolUse` hook then sees.
*/
ToolGroup: {
/**
* In the order the model made them.
*/
calls: ReadonlyArray<ToolGroupCall>;
/**
* True while the group is the live one: a call in it may still be
* running and the model's next call may join it.
*/
isActive: boolean;
/**
* Whether each call draws as its own `ToolUse` row (true under
* `--verbose` and in the ctrl+o transcript) or the group draws one line.
*
* The one prop of the three a rewrite changes on the screen.
*/
isExpanded: boolean;
};
/**
* The output row a slash command printed in the transcript, under its echo
* (`/cost`'s lines, the `text` a `command.run` hook answered).
*
* What the run resolved as text, a `local` command's or a plugin's alike. A
* rewrite of `text` draws there and the stored row keeps what the model
* reads; a hook's own tree draws in the row's place, the transcript's width.
*/
CommandOutput: {
/**
* Which one printed the row, as `command.run` named it (no slash); a
* hook on its own command matches by it.
*
* Read-only: a rewrite carries it on as received; one that changes or
* drops it is refused and the engine draws its own row.
*/
command: string;
/**
* The arguments the run had, as the echo above the row shows them
* (`***` for a command that marks its arguments sensitive). Read-only.
*/
args: string;
/**
* The row's text: what the command printed, or the `text` a hook
* answered under its plugin's name; markdown, as the row draws it.
*/
text: string;
/**
* True when the row is the run's error line (a command that threw),
* which draws in the error colour and not dim. Read-only.
*/
isErrored: boolean;
};
/**
* The line that animates while a turn runs (`Sauteing... (12s, 300
* tokens)`). Terminal only: the Code session renderer draws its own.
*/
Spinner: {
/**
* Animated by the line (`Sauteing`), as sampled for this turn.
*/
word: string;
/**
* The text drawn instead of the word while a state overrides it, else null.
*/
message: string | null;
/**
* What the turn is doing.
*/
mode: 'requesting' | 'responding' | 'thinking' | 'tool-input' | 'tool-use';
};
/**
* The line that closes a turn in the transcript (`Baked for 3s`).
* Terminal only: the Code session renderer draws its own footer.
*/
TurnDuration: {
/**
* The past-tense word the line drew (`Baked`), as sampled for this line.
*/
word: string;
/**
* The turn's duration in milliseconds, as the line formats it (`3s`,
* `1m 4s`).
*/
durationMs: number;
};
/**
* One dim status line under the logo (the model source, an experiment
* enrollment, a settings hint), with a trailing `/command`. Terminal only.
*/
InfoNotice: {
/**
* The notice's text, flattened to one string.
*/
text: string;
/**
* The slash command appended after the text, or null when the notice has
* none.
*/
command: string | null;
};
/**
* The dim mode labels at the right of the prompt footer (`focus`, `memory
* paused`), joined by ` & `. One instance; terminal only.
*
* A hook adds a mode by rewriting `modes`, removes one by filtering, or
* draws its own tree.
*/
SessionMode: {
/**
* The labels the footer shows, in order; empty when there are none.
*/
modes: readonly string[];
};
/**
* The dim hint line under the prompt (`? for shortcuts`, `esc to
* interrupt`, the pills beside them). One instance; terminal only.
*
* A hook rewrites `hint` and the rewrite is drawn in the line's place, or
* draws its own tree; `isDraft` and `isWorking` say what the line is for.
*/
PromptHint: {
/**
* True while the prompt holds typed text. Read-only.
*/
isDraft: boolean;
/**
* True while a model turn is running. Read-only.
*/
isWorking: boolean;
/**
* The line's text as the engine draws it; one string, so a rewrite
* replaces the line.
*
* Read from the drawn line the way the screen reader reads it, one space
* between parts.
*/
hint: string;
};
/**
* The band directly above the prompt input, where the surveys draw; the
* engine draws nothing of its own here.
*
* A hook draws a tree, or passes; one instance, terminal only. The person
* collapses it (ctrl+x ctrl+a, `[-]`) or focuses it (a click, ctrl+x tab):
* an Input types, a Button arms the hotkeys, a tree taller than it scrolls.
*/
AbovePrompt: {
/**
* True while a survey holds the band; a hook yields to it. Read-only.
*/
hasSurvey: boolean;
/**
* True while a model turn is running. Read-only.
*/
isWorking: boolean;
/**
* Rows the band may take: in fullscreen, what the bottom slot has left
* above the prompt; otherwise the terminal's height. Read-only.
*
* A tree of at most `maxRows` rows shows whole; a taller one scrolls in a
* window of `scroll.bodyRows` (one fewer, over a dim `n more` row), and a
* bare digit arms none of its Buttons' hotkeys.
*/
maxRows: number;
/**
* Cells across the band: the terminal's width, or the transcript
* column's while a `Pane` is docked beside it. Read-only.
*
* A tree wider than this wraps or truncates as its Text props say; size
* a table or a rule to it rather than to `viewport.columns`.
*/
bodyColumns: number;
/**
* The band's window over a tree taller than `maxRows`: engine-owned,
* moved by the wheel, and by the person's keys while the band is focused.
*
* `bodyRows` is `maxRows` less the `n more` row. Read-only.
*/
scroll: SiteScroll;
/**
* Which transcript is on screen above the band: the main conversation's
* (no `agentId`) or one agent's, opened from the tasks list.
*
* The same band under either; a switch re-runs the hook with the new
* view. Read-only: a rewrite carries it on as received; one that changes
* or drops it is refused, the hook that passed it failing.
*/
view: SiteView;
};
/**
* The framed region a plugin opened with `$.ui.open({ id })`: one instance
* per id (`requestId`), its body the hook's tree, one shown, the rest tabs.
*
* Placed by the surface (docked in fullscreen, else above the prompt) and
* keyed by the person (ctrl+x tab, Esc), who closes it from the engine's mark
* or ctrl+x x: `ui.close` with origin `person`, which a hook may refuse.
*/
Pane: {
/**
* Its tab's label while more than one pane is open (with one, the engine
* draws no title): the `title` it was opened with, or its id.
*
* A click on a tab, or Tab onto it and Enter, shows that pane. Read-only
* here; another `$.ui.open` (or a hook on `ui.open`) retitles.
*/
title: string;
/**
* True while the person has given the pane the keyboard. Read-only.
*/
isFocused: boolean;
/**
* Cells across the body, inside the frame. Read-only.
*/
bodyColumns: number;
/**
* Where the surface seated the pane: `dock` beside the transcript (the
* terminal in fullscreen from 110 columns), or `inline` above the prompt.
*
* Read-only: a rewrite carries it on as received; one that changes or
* drops it is refused, the hook that passed it failing.
*/
placement: 'dock' | 'inline';
/**
* The body's window over the tree: engine-owned, moved by the person's
* keys while the pane is focused. Read-only.
*/
scroll: SiteScroll;
/**
* Which transcript is on screen beside the pane: the main conversation's
* (no `agentId`) or one agent's, opened from the tasks list.
*
* The pane stays open across a switch, one instance re-rendered for the
* view, so a hook draws for the agent in view. Read-only: a rewrite carries
* it on as received; one that changes or drops it is refused.
*/
view: SiteView;
};
};
/**
* What a `ui.render` hook returns and what `next(e)` resolves to: a
* RenderElement tree, the same for every component.
*/
export type RenderResultOf = {
[C in RenderComponent]: RenderElement;
};
/**
* Where a render event's component is drawn: `terminal` is Ink, which draws
* the hook's whole tree; the rest are remote surfaces drawing it themselves.
*
* `desktop` is Claude Code Desktop, `mobile` the Claude mobile app, `vscode`
* Claude Code for VS Code. A remote surface asks over the wire (ui_render),
* draws with the props the hook handed core, and draws the tree where it has
* a slot for it.
*
* Each surface's ask is its own evaluation, since a tree may hold an element
* only some surfaces draw (Svg, Client).
*/
export type RenderSurface = 'terminal' | 'desktop' | 'mobile' | 'vscode';
/**
* The size of what a surface draws into, in character cells of the
* surface's monospace metric, and whether its layout docks a pane.
*
* On the terminal, the conversation's columns and screen rows; on a remote
* surface, the pane's width and height over the advance and line height of
* its code font. Cell-based until the first element lays out in pixels.
*/
export type RenderViewport = {
/**
* Cells across. A tree wider than this wraps or truncates, as its Text
* props say.
*/
columns: number;
/**
* Cells down the whole surface, not the room left for this component.
*
* Informational: a change of height alone re-draws nothing and keys no
* new evaluation, so a hook reads it as of the last width or props change.
*/
rows: number;
/**
* Whether this surface docks a pane beside the transcript, so a pane a
* plugin opens unasked is a sidebar, not a takeover; absent is unknown.
*
* What `command.run`'s `presentation.isFullscreen` says. The terminal always
* says: `true` fullscreen, `false` on the main screen, fixed per session; a
* remote surface once its client reports it with the size, absent before.
*
* @remarks The desktop and VS Code report it once they place panes; the
* mobile app, which has no dock, `false`. A change re-draws the sites.
* @example if (e.viewport?.isFullscreen === true) void $.ui.open({ id })
*/
isFullscreen?: boolean;
};
/**
* The input of `ui.resolve`: which surface's elements, for which component;
* a union with one member per surface (ResolveInputOf).
*
* Resolved when the plugins load, ahead of any drawing, so it names the
* surface and the component and not the props; a `ui.render` argument is
* one (it carries both), which is what `$.ui.resolve(e)` takes.
*/
export type ResolveInput<C extends RenderComponent = RenderComponent, P extends RenderSurface = RenderSurface> = P extends RenderSurface ? ResolveInputOf<C, P> : never;
/**
* One `ui.resolve` input, for a component on one surface.
*/
export type ResolveInputOf<C extends RenderComponent, P extends RenderSurface> = {
/**
* Where the table draws; one literal per member, so a hook that narrows
* it narrows the table `next(e)` resolves to.
*/
surface: P;
/**
* Which drawing the table is resolved for; the key a matcher narrows on.
*/
component: C;
};
/**
* What each event's hook returns, and what its `next(e)` resolves to, by event
* name.
*/
export type ResultOf = EngineResultOf & ClassicResultOf & {
[N in OpEventName]: OpEventResult<N>;
} & {
[N in NounEventName]: NounEventResult<N>;
};
type SDKAssistantMessageError = 'authentication_failed' | 'oauth_org_not_allowed' | 'account_on_hold' | 'verification_required' | 'billing_error' | 'rate_limit' | 'overloaded' | 'invalid_request' | 'model_not_found' | 'server_error' | 'unknown' | 'max_output_tokens' | 'cloud_credential_error';
/**
* The members of `T` assignable to `S`; all of `T` when none is.
*/
type Select<T, S> = [Extract<T, S>] extends [never] ? T : Extract<T, S>;
/**
* The events a pattern selects, as a union of names: the one named, every
* one under a glob's namespace, or every one a negation does not exclude.
*/
export type Selected<P extends string> = P extends '*' ? EventName : P extends `!${infer Negated}` ? Exclude<EventName, Selected<Negated>> : P extends `${infer Prefix}.*` ? Extract<EventName, `${Prefix}.${string}`> : Extract<EventName, P>;
/**
* The literal each tag key of `I` is held to by matcher `M`: one-of arrays
* flattened, RegExps widened to `unknown`.
*/
type Selection<I, M> = {
[K in keyof M & TagKeys<I>]: Literal<M[K] extends readonly (infer One)[] ? One : M[K]>;
};
/**
* One option of a `Select`: the value `onSelect` and `ui.select` carry, and
* the text drawn for it (the value when absent).
*/
export type SelectOption = {
value: string;
label?: string;
};
/**
* The props of `Select`, every surface's one-of-several picker: an address,
* a label, the options, the one selected, the closure a pick runs. A leaf.
*
* Focused through the same ring as `Button` (`abovePrompt:focus`); keys reach
* it only while it has focus (arrows move, Enter picks) and Esc always
* returns to the prompt; a pick raises `ui.select`, its bottom `onSelect`.
*/
export type SelectProps = {
/**
* The element's address: `e.element` at `ui.select`, what a matcher names.
*/
key: string;
/**
* Text drawn before the current value.
*/
label?: string;
/**
* What can be picked, in the order drawn; at least one, values unique.
*/
options: readonly SelectOption[];
/**
* Which option is selected when drawn; the person's pick replaces it
* until the hook draws another.
*/
value?: string;
/**
* The site's focus ring starts here when the site takes the keyboard,
* instead of on nothing, as the DOM's `autofocus`: Enter acts on it at once.
*
* A pane opened with `focus`, or the person's focus chord or click, is the
* take. Of several in one site the first drawn wins; it raises `ui.focus`,
* origin this plugin. A ring the person has moved stays where it was put.
*/
autoFocus?: true;
/**
* Runs on a pick with the option's value, in the plugin's own environment:
* the bottom of a `ui.select` chain. No model turn unless it asks one.
*/
onSelect: (value: string, e: UiSelectArgument) => void;
};
/**
* The input of `session.attach`: a surface joined the session's roster of
* attached clients (a phone opened the session; the desktop app connected).
*
* A remote client attaches by saying so (ui_attach) or by its first ask to
* draw; the terminal's attachment is the REPL's binding and raises nothing.
* Every field is the engine's: a hook observes, `next(e)` passes them on.
*/
export type SessionAttachInput = {
/**
* Where the client draws: what it declared, a rendering fact.
*/
surface: RenderSurface;
/**
* The client's own id, unique in the roster; two phones are two clients on
* one surface. A client that never named itself is `<surface>:default`.
*/
clientId: string;
/**
* The size the client draws into, in character cells, when it said.
*/
viewport?: RenderViewport;
};
/**
* What a `session.attach` hook returns and what `next(e)` resolves to:
* `{ clientId }`, echoed by core; a hook's own value changes nothing.
*/
export type SessionAttachResult = {
clientId: string;
};
/**
* What `$.session.authorize()` answers: an opaque handle for the session's
* Anthropic credential and its kind, or null when there is none to hold.
*
* The secret itself stays with the engine; the handle is its plugin-side
* face, spent through `$.http.fetch(url, { auth: handle })`.
*/
export type SessionAuthorization = {
handle: string;
kind: 'bearer' | 'api-key';
} | null;
/**
* `session.compact`'s input as a plugin's `$.session.compact(args)` takes
* it: `trigger` (`plugin`), `messages` and `agentId` are the engine's.
*/
export type SessionCompactArgs = {
/**
* What the summary should keep or stress, as typed after `/compact`;
* absent, the engine's own compaction prompt alone.
*/
instructions?: string;
};
/**
* A compaction that stands: the conversation as it reads afterwards, and
* the token counts the engine recorded when it was the one compacting.
*/
export type SessionCompacted = {
/**
* The conversation after the compaction, oldest first: from core, its
* summary and the messages it kept; from a hook, whatever it hands up.
*
* What the transcript becomes (kept, on `precompute`, for the compaction
* that comes). A message with the engine's `handle` stands as the engine
* has it; one without is built from its `role`, `text` and tool blocks.
*/
messages: readonly SessionMessage[];
/**
* The conversation's size before, in tokens; absent when core did not
* record it.
*/
tokensBefore?: number;
/**
* Its size afterwards, in tokens; absent on `precompute` and when core
* did not record it.
*/
tokensAfter?: number;
skip?: undefined;
};
/**
* The input of `session.compact`: one compaction of the conversation, about
* to run; `messages` is the transcript it runs over.
*/
export type SessionCompactInput = {
/**
* What is compacting (SessionCompactTrigger); the key a matcher narrows
* on. Pinned: `next(e)` passes it on as received.
*/
trigger: SessionCompactTrigger;
/**
* The id of the loop compacting, for a subagent's or a fork's own
* transcript; absent for the main conversation (tool.call's `agentId`).
*
* Pinned: left out of a rewrite it is put back, changed it fails the hook.
* `$.session.messages()` is the main conversation whatever this names.
*/
agentId?: string;
/**
* What the summary should keep or stress: the text after `/compact`, a
* plugin's, or absent.
*
* `next({ ...e, instructions })` changes what the summarizer is told.
*/
instructions?: string;
/**
* The transcript being compacted, in `$.session.messages()`'s shape, each
* message carrying the engine's `handle`; a subagent's own under `agentId`.
*
* `next({ ...e, messages })` changes what is summarized: a message kept
* with its handle is the engine's own, whole; one without is read as built.
*/
messages: readonly SessionMessage[];
};
/**
* What a `session.compact` hook returns and what `next(e)` resolves to: the
* compaction (`{ messages, tokensBefore?, tokensAfter? }`) or `{ skip }`.
*
* There is no summary string: the summary is a message.
*/
export type SessionCompactResult = SessionCompacted | SessionCompactSkipped;
/**
* A compaction vetoed: on `precompute` nothing is computed or kept; on any
* other trigger the conversation stays as it is and one line says why.
*
* Core answers it too, when a classic PreCompact hook blocks.
*/
export type SessionCompactSkipped = {
/**
* Why, as the notice reads.
*/
skip: string;
messages?: undefined;
};
/**
* Who compacts: the person's `/compact` (`manual`), the engine at its
* threshold or on a prompt too long (`auto`), a plugin, or a `precompute`.
*
* `precompute` is the one dispatch that installs nothing: its result is kept
* for the compaction that comes, if the conversation it ran over still leads.
*/
export type SessionCompactTrigger = 'manual' | 'auto' | 'plugin' | 'precompute';
/**
* The context window broken down as /context breaks it down: the rows, the
* grid and the lists beneath it, in the SDK's `get_context_usage` shape.
*
* Less that reply's internal-build sections. Token counts are the engine's
* estimates as numbers, never formatted: a `full` breakdown counts with the
* token-count API where it can, a `summary` one estimates throughout.
*/
export type SessionContextBreakdown = {
/**
* One row per category, the free space and the compaction buffer among
* them; `kind` says which is which.
*/
categories: ContextCategory[];
/**
* Tokens in use, unclamped: past `rawMaxTokens` when over the window.
*/
totalTokens: number;
/**
* The window measured against, the same figure as `rawMaxTokens`.
*/
maxTokens: number;
/**
* The window measured against, in tokens: the model's limit, or a smaller
* compaction window (`autocompactSource` says which).
*/
rawMaxTokens: number;
/**
* How that window was settled (ContextWindowSource); the SDK's reply
* carries it under this name too, outside its typed schema.
*/
autocompactSource: ContextWindowSource;
/**
* `totalTokens` over `rawMaxTokens` as a whole percentage, 0 to 100 and
* past it when over.
*/
percentage: number;
/**
* The grid, row by row: 10 by 10, 20 by 10 for a window of a million or
* more, 5 wide when asked for under 80 `columns`.
*/
gridRows: ContextGridSquare[][];
/**
* Which model the breakdown was computed for, as `/model` shows it.
*/
model: string;
/**
* Each memory file in the context, with its path and tokens.
*/
memoryFiles: ContextMemoryFile[];
/**
* Each MCP tool's schema, with its server and tokens.
*/
mcpTools: ContextMcpTool[];
/**
* The custom agents the Agent tool describes, each with its tokens.
*/
agents: ContextAgent[];
/**
* The slash-command listing, counted; absent when the session lists none.
*/
slashCommands?: ContextSlashCommands;
/**
* The skill listing, counted, with one entry per skill; absent when the
* session lists none.
*/
skills?: ContextSkills;
/**
* The token count at which auto-compaction runs; absent when it is off.
*/
autoCompactThreshold?: number;
/**
* Whether auto-compaction is on for the session.
*/
isAutoCompactEnabled: boolean;
/**
* The last response's own token counts, or null before one came back.
*/
apiUsage: ContextApiUsage | null;
};
/**
* The live context window as the status line reads it, and by category as
* /context breaks it down when the call asked (`{ breakdown }`).
*
* `tokens` and `percent` are the last API response's input side against the
* model's window, absent until the first response of the live window: a
* fresh session, or one just compacted, until its next response.
*/
export type SessionContextUsage = {
/**
* Input tokens the last response was answered over: uncached, cache-written
* and cache-read together (the status line's `total_input_tokens`).
*/
tokens?: number;
/**
* The context window of the session's model, in tokens (the status line's
* `context_window_size`).
*/
window: number;
/**
* `tokens` over `window` as a whole percentage, 0 to 100 (the status
* line's `used_percentage`).
*/
percent?: number;
/**
* The window by category, as /context breaks it down: present only when
* the call passed `breakdown`, and only with a session bound.
*
* It measures against the compaction window (`rawMaxTokens`), which may be
* smaller than `window`, and estimates every category, so its
* `totalTokens` need not equal `tokens`.
*/
breakdown?: SessionContextBreakdown;
};
/**
* What the session has cost, as `/cost` and the status line total it.
*/
export type SessionCost = {
/**
* US dollars, summed over every priced API response this session.
*/
usd: number;
};
type SessionCronSummary = {
id: string;
/**
* Cron expression, e.g. "0 9 * * 1-5".
*/
schedule: string;
/**
* False for one-shot wakeups whose cron field encodes a single fire time; true for tasks that re-fire on every match.
*/
recurring: boolean;
/**
* Prompt text submitted when the cron fires. Capped at 1000 chars; clipped values append an in-string "... [+N chars]" marker.
*/
prompt: string;
};
/**
* The input of `session.detach`: a client left the session's roster. Every
* field is the engine's: a hook observes, and `next(e)` passes them on.
*/
export type SessionDetachInput = {
/**
* Where the client drew.
*/
surface: RenderSurface;
/**
* The id it attached under.
*/
clientId: string;
/**
* Why it left: it detached, or the session ended under it.
*/
reason: SessionDetachReason;
};
/**
* Why a client left the roster: `detach`, it said so (ui_detach); `end`, the
* session ended with it still attached.
*/
export type SessionDetachReason = 'detach' | 'end';
/**
* What a `session.detach` hook returns and what `next(e)` resolves to:
* `{ clientId }`, echoed by core; a hook's own value changes nothing.
*/
export type SessionDetachResult = {
clientId: string;
};
type SessionEndHookInput = BaseHookInput & {
hook_event_name: 'SessionEnd';
reason: ExitReason;
};
/**
* One message of the transcript as `$.session.messages()` returns it.
*/
export type SessionMessage = {
/**
* Who wrote it.
*/
role: 'user' | 'assistant';
/**
* Its text blocks joined; '' when it has none.
*/
text: string;
/**
* The tool_use blocks of an assistant message, each with its outcome
* (`result`, `text`, `isError`) once the transcript holds it.
*/
toolUses: ToolUseSummary[];
/**
* The tool_result blocks of a user message: `{ tool_use_id, text, isError,
* result }`.
*/
toolResults?: ToolResultSummary[];
/**
* An opaque token the engine stamps on a message it hands a
* `session.compact` hook, so a list handed back maps to its own messages.
*
* Absent on `$.session.messages()` and on a message a hook built.
*/
handle?: string;
};
/**
* One rate-limit window as the rate-limit notices read it.
*/
export type SessionRateLimit = {
/**
* Which window: `five_hour`, `seven_day`, or a Claude gateway's
* `spend_limit`.
*/
kind: string;
/**
* How much of the window is used, 0 to 100 (above 100 once a spend limit
* is exceeded).
*/
percentUsed: number;
/**
* When the window resets, as an ISO 8601 timestamp.
*/
resetsAt?: string;
};
/**
* An external-event wake the delivery's text parsed as (a GitHub relay
* event, a signal's notice): the envelope's attributes and its JSON body.
*/
export type SessionReceiveEvent = {
/**
* The producing service (`github`).
*/
source: string;
/**
* The event's discriminator (`pull_request.closed`, `check_suite`).
*/
kind: string;
/**
* The envelope's JSON body (`{ pr: "acme/app#12", outcome: "merged" }`).
*/
data: Record<string, unknown>;
/**
* The `data` keys whose values are free text a third party wrote (a
* commenter's `author` and `comment`), as the producer marked them.
*
* Empty when none; the server asserts every other key's value, not these.
*/
untrustedKeys: readonly string[];
};
/**
* The input of `session.receive`: one inbound delivery (a relay's event, a
* peer's message, a Remote Control prompt), sanitized, before it is queued.
*/
export type SessionReceiveInput = {
/**
* Where the delivery came from, as the bridge classified it; the key a
* matcher narrows on. `next(e)` passes it on as received.
*/
origin: SessionReceiveOrigin;
/**
* The delivery's body as the model would read it (a content-block
* delivery's text blocks, joined).
*/
text: string;
/**
* The external-event wake the text parsed as (`source` `github` for a
* subscribed pull request's event); passed on as received.
*
* Present only for a delivery the server itself rendered as a wake (a
* webhook relay, the session inbox), by its asserted origin; anyone else's
* wake-shaped text stays `text`. Its `untrustedKeys` name third-party text.
*/
event?: SessionReceiveEvent;
};
/**
* Where an inbound delivery came from, as the bridge classified it from the
* server's stamps: `prompt.submit`'s `e.origin`, less what never arrives.
*/
export type SessionReceiveOrigin = {
/**
* `bridge` the user's own from a Remote Control client; `peer` another
* session; `unclassified` one the bridge could not place.
*
* `task-notification` a relay's event (a GitHub webhook) or a trigger;
* `scheduled-trigger` a routine; `peer-send-message` another session's
* SendMessage; `projects-relay` and `slack-ping` as at `prompt.submit`.
*/
kind: 'bridge' | 'task-notification' | 'scheduled-trigger' | 'peer' | 'peer-send-message' | 'projects-relay' | 'slack-ping' | 'unclassified';
};
/**
* What a `session.receive` hook returns and what `next(e)` resolves to: the
* delivery that was queued, `{ text }`, or `{ consumed: reason }`.
*
* `next(e)` resolves once the delivery is queued; a hook answering without
* `next` queues nothing.
*/
export type SessionReceiveResult = {
/**
* The body the delivery was queued with; from core, `e.text` as it
* arrived at the bottom.
*
* A rewrite passes it down, `next({ ...e, text })`.
*/
text: string;
consumed?: undefined;
} | {
/**
* Takes the delivery, answered without `next`: it is not queued, not
* written to the transcript and never reaches the model.
*
* The reason is logged, the plugin named.
*/
consumed: string;
text?: undefined;
};
/**
* What `$.session.repo()` answers: the repository's root and its origin remote,
* when the session is in one.
*/
export type SessionRepo = {
/**
* The repository's root, absolute: the main working tree's for a worktree.
*/
root: string;
/**
* The `origin` remote's URL as git has it (push URL preferred), or null when
* the repository has none.
*/
remote: string | null;
/**
* Whether the remote is one of the repositories this build treats as its
* own; false in a build that has none or when the remote is unrecognized.
*
* The engine matches the build's own list of repositories with its
* hardened remote parser. A plugin reads this to behave differently in a
* public repository; which repositories are the build's is its to say.
*/
internal: boolean;
/**
* The repository the allowlist matched, as `owner/name`; null when
* `internal` is false.
*
* A working copy without a remote that the engine still recognises is
* named by its own checkout configuration; a remote's name is its path.
*/
name: string | null;
};
type SessionStartHookInput = BaseHookInput & {
hook_event_name: 'SessionStart';
source: 'startup' | 'resume' | 'clear' | 'compact' | 'fork';
agent_type?: string;
model?: string;
session_title?: string;
/**
* resume/fork: seconds since the resumed transcript's last assistant response
*/
seconds_since_last_response?: number;
/**
* resume/fork: the resumed transcript's last response input + cache_read + cache_creation + output tokens (for a server-side tool loop, its last iteration's window, not the summed totals)
*/
context_tokens?: number;
/**
* resume/fork: seconds_since_last_response exceeds the prompt-cache TTL, so the first request re-caches context_tokens
*/
prompt_cache_likely_expired?: boolean;
/**
* resume/fork: estimated cost of re-caching context_tokens on the session model - the managed modelPricing when set, otherwise list price; excludes the response
*/
estimated_cache_write_usd?: number;
};
/**
* The input of `session.start`: the session the process starts with, read the
* way `$.session` reads it at that moment.
*/
export type SessionStartInput = {
/**
* The directory the session runs in, absolute (`$.session.cwd()`).
*/
cwd: string;
/**
* Where the session draws at start (`$.session.surfaces()[0]`): `terminal`
* under the REPL; null for a `-p` run or the SDK, which draw nowhere yet.
*/
surface: RenderSurface | null;
/**
* Whether a person is at the prompt: true under the REPL, false for a `-p`
* run or the SDK.
*/
isInteractive: boolean;
};
/**
* What a `session.start` hook returns and what `next(e)` resolves to:
* `{ cwd }`, echoed by core; a hook's own value does not change the session.
*/
export type SessionStartResult = {
cwd: string;
};
/**
* What `$.session.usage()` answers: the context window's fill, the account's
* rate-limit windows and the session's cost, as the status line has them.
*
* A figure the engine does not have is left out, never zeroed: `rateLimits`
* is empty off a subscription, `cost` absent where the host keeps no ledger.
*/
export type SessionUsage = {
/**
* The live context window: the status line's `context_window` figures.
*/
context: SessionContextUsage;
/**
* The rate-limit windows the last API response reported (`five_hour`,
* `seven_day`, a gateway's `spend_limit`); empty when none has a reading.
*/
rateLimits: SessionRateLimit[];
/**
* What the session has cost so far, as /cost totals it; absent only where
* the host keeps no cost ledger (the CLI always has one).
*/
cost?: SessionCost;
};
/**
* What `$.session.usage(args)` takes: nothing for the status line's figures
* alone; `breakdown` to have the window broken down as /context breaks it.
*/
export type SessionUsageArgs = {
/**
* Asks for `context.breakdown` and says how it is counted
* (ContextBreakdownDetail); absent, none is computed and the call is free.
*
* `full` sends one token-count request per tool and memory file, as
* /context does; `summary` estimates locally and sends none.
*/
breakdown?: ContextBreakdownDetail;
/**
* The width the breakdown's grid will be drawn in, in terminal columns;
* absent, the full-width grid. Read only with `breakdown`.
*
* Under 80 the grid is the narrow one /context draws there, 5 wide. A thin
* client's breakdown is the remote workspace's, whose grid ignores this.
*/
columns?: number;
};
/**
* What `$.settings.read` answers: an object keyed as a settings.json is
* (`permissions`, `env`, `hooks`, `model`, `enabledPlugins`, ...).
*
* Each key is as https://code.claude.com/docs/en/settings documents it and
* https://json.schemastore.org/claude-code-settings.json types it. A
* snapshot in plain data: a write to it changes nothing the engine reads.
*/
export type Settings = Readonly<Record<string, unknown>>;
/**
* What `$.settings.read(args)` takes.
*/
export type SettingsReadArgs = {
/**
* The one source read, as loaded; absent, the settings merged over every
* source, as the engine runs under them.
*/
source?: SettingsSource;
};
/**
* One source of settings by the name a plugin gives it, lowest precedence
* first; the engine's own name is the same word with `Settings` appended.
*
* `user` is ~/.claude/settings.json, `project` .claude/settings.json,
* `local` .claude/settings.local.json, `flag` what `--settings` and the
* SDK's inline settings carry, and `policy` the managed settings, every
* managed tier merged.
*/
export type SettingsSource = 'user' | 'project' | 'local' | 'flag' | 'policy';
type SetupHookInput = BaseHookInput & {
hook_event_name: 'Setup';
trigger: 'init' | 'maintenance';
};
/**
* Where a site's window sits over the tree a hook drew in it (a pane's body,
* the band): the engine's to move (the person scrolls), the plugin's to read.
*/
export type SiteScroll = {
/**
* The first row of the tree the window shows; 0 at the top. Read-only.
*/
offset: number;
/**
* How many rows of the tree the window shows at once: the rows the
* surface gave the body. Read-only.
*/
bodyRows: number;
};
/**
* Which transcript the person has on screen where a site draws: the main
* conversation's, or one agent's, opened from the tasks list.
*
* The person's to switch, the plugin's to read: a switch re-runs the site's
* hooks with the new view, the site itself staying where it is.
*/
export type SiteView = {
/**
* The agent whose transcript is in view: the `id` `$.agent.list()` gives
* it, the `agentId` its `turn.step` and `tool.call` events carry.
*
* Absent while the main conversation is in view. Read-only.
*/
agentId?: string;
};
/**
* The input of `skill.prompt`: one skill's prompt, at the moment the engine
* expanded it for the model.
*
* Typed as `/name`, called through the Skill tool, or preloaded into a
* subagent: the same event at each.
*/
export type SkillPromptInput = {
/**
* Which skill (`commit`); the key a matcher narrows on.
*/
skill: string;
/**
* The prompt's text as the skill computed it (its text blocks, joined).
*/
text: string;
};
/**
* What a `skill.prompt` hook returns: the text the model reads for that
* skill.
*/
export type SkillPromptResult = {
text: string;
};
/**
* Options of `$.clock.sleep`.
*/
export type SleepOptions = {
/**
* Aborting it rejects the sleep at once.
*/
signal?: AbortSignal;
};
/**
* Options of `$.audio.speak`.
*/
export type SpeakOptions = {
/**
* The system voice's exact name as the platform lists it (`Samantha`, or the
* name of a voice you installed). Absent: the synthesizer's default voice.
*/
voice?: string;
};
/**
* The argument of `$.audio.speak(text, options)` as the event carries it.
*/
type SpeakRequest = SpeakOptions & {
/**
* What to say, as plain text, of at most 4096 characters.
*/
text: string;
};
/**
* What `$.audio.speak` resolves with once the utterance has ended.
*/
export type SpeakResult = {
/**
* Which synthesizer spoke: `system`, the platform's own (`say` on macOS).
*/
via: 'system';
};
/**
* `next` in a `*` hook: the set of events is open at runtime, so `e` is
* `unknown` until `next.is(pattern, e)` narrows it to events it knows.
*
* The callable is an overload per known event (OrderedOverloads), then
* `(e: unknown) => Promise<unknown>` last: `next(e)` with `e` still unknown
* resolves to `unknown`.
*/
export type StarNext = OrderedOverloads<EventName> & {
(e: unknown): Promise<unknown>;
/**
* Continues this dispatch at a tier, as Next's `to` (a managed hook's):
* `e` still unknown resolves to `unknown`.
*/
readonly to: (e: unknown, tier: TargetTier) => Promise<unknown>;
readonly signal: AbortSignal;
readonly is: <M extends Pattern>(pattern: M, e: unknown) => e is Frozen<Args<Selected<M>>>;
readonly event: EventName;
readonly origin: Origin;
readonly trace: readonly TraceEntry<EventName, unknown, unknown>[];
};
type StopFailureHookInput = BaseHookInput & {
hook_event_name: 'StopFailure';
error: SDKAssistantMessageError;
error_details?: string;
last_assistant_message?: string;
};
type StopHookInput = BaseHookInput & {
hook_event_name: 'Stop';
stop_hook_active: boolean;
/**
* Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.
*/
last_assistant_message?: string;
/**
* In-flight background work (running/pending + backgrounded) registered in this session. Lets hooks distinguish "session is done" from "session is paused waiting for background work to wake it". Empty array when nothing is in flight.
*/
background_tasks?: BackgroundTaskSummary[];
/**
* Session-scoped cron tasks (CronCreate, ScheduleWakeup, /loop) that will wake this session later. Empty array when none are scheduled.
*/
session_crons?: SessionCronSummary[];
};
/**
* The hook a streaming event takes: `async function* ($, e, next) {}`,
* yielding the event's chunks and returning its result.
*
* `return yield* next(e)` passes; `for await (const c of next(e)) yield
* f(c)` transforms; yielding without `next` answers alone. A chunk yielded
* stays: a hook that fails mid-stream is left, the rest from beneath it.
*
* @example on('turn.step', async function* ($, e, next) {
* const r = yield* next(e); return { ...r } })
*/
export type StreamHook<N extends StreamingEventName> = ($: EngineInterface, e: Frozen<Args<N>>, next: StreamNext<N>) => StreamHookBody<Chunk<N>, EventResult<N>>;
/**
* What a hook on a streaming event evaluates to: the async generator an
* `async function*` makes, yielding `C` and returning `R` or nothing.
*
* Returning nothing lets its last `next(e)`'s result stand. A plain
* function is a type error here even when it returns `next(e)`: the hook
* is the generator, not a function that hands one back.
*/
export type StreamHookBody<C, R> = AsyncGenerator<C, R | void> & {
/**
* Absent on a generator; present on `next(e)`, which is not a hook body.
*/
readonly result?: never;
};
/**
* The events that stream: their hooks are async generators, `next(e)` is
* the stream of everything beneath, and the result is what it returns.
*
* `turn.step` alone: the model's response arrives in pieces, and a hook
* that saw it whole could not change what had already been shown.
*/
export type StreamingEventName = 'turn.step';
/**
* The rest of the chain as a hook on a streaming event receives it: Next,
* except that `next(e)` is the stream beneath (HookStream), not a promise.
*
* Each call opens a fresh stream; for `turn.step` each is a model request,
* so a hook that calls it twice makes two. Not calling it yields the hook's
* own chunks and returns its own result, and nothing beneath runs.
*
* @template S what `next.is(pattern, e)` narrows `e` to, as Next's
*/
export type StreamNext<N extends StreamingEventName = StreamingEventName, E = Args<N>, O = NextResult<N>, S extends {
[K in N]?: unknown;
} = {
[K in N]: Args<K>;
}> = Pick<Next<N, E, O, S>, 'signal' | 'is' | 'event' | 'origin'> & {
(e: E): HookStream<Chunk<N>, O>;
/**
* Continues this dispatch at a tier, as Next's `to`: the stream beneath
* with the links between this hook's tier and that one skipped.
*/
readonly to: (e: E, tier: TargetTier) => HookStream<Chunk<N>, O>;
/**
* What settled beneath on the latest `next()` stream, as Next's; a
* streaming link's entry counts the chunks it yielded up (`chunks`).
*/
readonly trace: readonly TraceEntry<N, E, O>[];
};
/**
* The shape a `Box` and a `Text` share in a render tree: allowlisted props,
* an optional `hover`, the group stamp a `hover.scope` earns, and children.
*
* `Tag` is which of the two; `Hover` is that element's hover props. Every
* surface draws both: Ink's Box and Text on the terminal, a flex div and a
* styled span on the desktop.
*/
type StyledElement<Tag extends 'Box' | 'Text', Hover> = {
type: Tag;
/**
* A Box's layout, margin, padding and border props and the `key` that
* makes it a hover scope; a Text's colors and styles. Others are refused.
*/
props?: Record<string, string | number | boolean>;
/**
* Style overrides the surface applies while the pointer is over the
* nearest keyed Box, or over any member of the group `scope` names.
*
* Plain data, no hook. Never a layout change: `borderStyle` restyles a
* border the Box has, `display` only reveals a Box drawn `"none"` inside
* a keyed Box, and never in a scope.
*/
hover?: Hover;
/**
* Whose group `hover.scope` names; absent without a `scope`.
*/
group?: PluginStamp;
/**
* In order: a Box holds elements and strings (core wraps each string in
* a Text); a Text holds strings and inline elements, never an engine node.
*/
children?: RenderNode[];
};
type SubagentStartHookInput = BaseHookInput & {
hook_event_name: 'SubagentStart';
agent_id: string;
agent_type: string;
};
type SubagentStopHookInput = BaseHookInput & {
hook_event_name: 'SubagentStop';
stop_hook_active: boolean;
agent_id: string;
agent_transcript_path: string;
agent_type: string;
/**
* Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.
*/
last_assistant_message?: string;
/**
* In-flight background work (running/pending + backgrounded) registered in this session. Lets hooks distinguish "session is done" from "session is paused waiting for background work to wake it". Empty array when nothing is in flight.
*/
background_tasks?: BackgroundTaskSummary[];
/**
* Session-scoped cron tasks (CronCreate, ScheduleWakeup, /loop) that will wake this session later. Empty array when none are scheduled.
*/
session_crons?: SessionCronSummary[];
};
/**
* The props of `Svg`, the remote surfaces' vector leaf: the markup is the
* element's data, as a string is a Text's, drawn isolated.
*
* A leaf: no children. The surface never lets the markup reach the page
* (the engine bounds it; the desktop and the editor draw it as an image, or
* in a sandboxed frame when `isInteractive`; the mobile app in a web view).
*/
export type SvgProps = {
/**
* The SVG document, `<svg ...>...</svg>`, at most 131072 characters.
*/
source: string;
/**
* What the drawing says, for a reader that cannot see it; required, since
* a surface without the element draws nothing else of it.
*/
alt: string;
/**
* CSS pixels; absent, the box takes the markup's own width up to the slot.
*/
width?: number;
/**
* CSS pixels; absent, the markup's own height at the drawn width.
*/
height?: number;
/**
* `true` draws the SVG in a script-less sandboxed frame so hover, CSS
* `:hover`, SMIL animation and `<title>` tooltips work; absent, an image.
*
* It never enables script or event-handler attributes (the frame has no
* allow-scripts and the scrub strips them); presses that other plugins
* should observe go on an enclosing element.
*/
isInteractive?: boolean;
};
/**
* The keys of `I` a matcher may select variants by: literal-valued in every
* variant, and one literal per variant (IsDiscriminant).
*/
type TagKeys<I> = {
[K in MatcherKeys<I>]: IsLiteralValued<MatcherValueOf<I, K>> extends true ? IsDiscriminant<I, K> extends true ? K : never : never;
}[MatcherKeys<I>];
/**
* A tier `next.to(e, tier)` may name: one a floor can reach past a tier of
* less authority to, so never `prepend` or `user`, which nothing skips to.
*/
export type TargetTier = Exclude<Tier, 'prepend' | 'user'>;
type TaskCompletedHookInput = BaseHookInput & {
hook_event_name: 'TaskCompleted';
task_id: string;
task_subject: string;
task_description?: string;
teammate_name?: string;
/**
* @deprecated Sessions have a single implicit team; this carries the session-derived team name and will be removed in a future release.
*/
team_name?: string;
};
type TaskCreatedHookInput = BaseHookInput & {
hook_event_name: 'TaskCreated';
task_id: string;
task_subject: string;
task_description?: string;
teammate_name?: string;
/**
* @deprecated Sessions have a single implicit team; this carries the session-derived team name and will be removed in a future release.
*/
team_name?: string;
};
type TeammateIdleHookInput = BaseHookInput & {
hook_event_name: 'TeammateIdle';
teammate_name: string;
/**
* @deprecated Sessions have a single implicit team; this carries the session-derived team name and will be removed in a future release.
*/
team_name: string;
};
/**
* The `Text` props a `hover` may override (its colors and styles, not its
* wrapping) and `scope`, the hover group it joins; a `Button`'s label too.
*/
export type TextHoverProps = {
/**
* Names a hover group of this plugin's: every element it draws with the
* same `scope`, in any site on the surface, lights while any is hovered.
*
* Another plugin's elements under the same string are a different group.
* One to 64 characters, no control characters; no keyed Box needed. On the
* terminal a Text nested in a Text follows its group but cannot heat it.
*/
scope?: string;
color?: string;
backgroundColor?: string;
dimColor?: boolean;
bold?: boolean;
italic?: boolean;
underline?: boolean;
strikethrough?: boolean;
inverse?: boolean;
};
/**
* The props of `Text`: the color and style props of Ink's Text a tree may
* set. Colors are a theme key or a raw color.
*/
export type TextProps = {
/**
* Style overrides applied by the surface while the pointer is over the
* nearest enclosing keyed `Box`, or, given a `scope`, over its group.
*
* No hook runs and nothing crosses to the plugin. Refused outside a keyed
* Box unless it names a `scope`.
*/
hover?: TextHoverProps;
color?: string;
backgroundColor?: string;
dimColor?: boolean;
bold?: boolean;
italic?: boolean;
underline?: boolean;
strikethrough?: boolean;
inverse?: boolean;
wrap?: 'wrap' | 'end' | 'middle' | 'truncate' | 'truncate-start' | 'truncate-middle' | 'truncate-end';
};
/**
* One of the chain's five tiers (TIERS), outermost first; on every
* `next.trace` entry, and what `next.to(e, tier)` names.
*
* `prepend` and `append` are the managed plugins an administrator lists,
* `user` everything a person installs, `builtin` the plugins bundled in the
* binary, `core` the engine's innermost link.
*/
export type Tier = (typeof TIERS)[number];
/**
* The chain's five tiers, outermost first: earlier is outer is more
* authority, and same-event hooks nest in this order and no other way.
*
* The managed plugins an administrator prepends, everything a person
* installs, the managed plugins appended, the plugins bundled in the binary,
* the engine's innermost link; a built-in's `$` calls still raise everywhere.
*/
const TIERS: readonly ["prepend", "user", "append", "builtin", "core"];
/**
* A pending timer from `$.clock.after` / `$.clock.every`.
*/
export type Timer = {
/**
* Stops it; a stopped timer never fires again.
*/
cancel: () => void;
};
/**
* A timer on `$.clock` (`after`, `every`): `fn` runs after `ms` milliseconds,
* once or until `cancel()`.
*/
export type TimerCall = (ms: number, fn: () => void) => Timer;
/**
* Options of `$.ui.toast`.
*/
export type ToastOptions = {
/**
* How long the line stays, in milliseconds; default 4000.
*/
timeoutMs?: number;
};
/**
* `tool.call`'s input as the call takes it: `tool_use_id` and `agentId` may
* ride along (a hook passing its event's input on) and are dropped.
*
* The run gets its own id and runs in the session's loop.
*/
export type ToolCallArgs = ToolCallEnvelope extends infer I ? I extends ToolCallEnvelope ? Omit<I, 'tool_use_id'> & ToolCallReserved<I['tool']> : never : never;
/**
* The envelope the two tool events share: the tool, the id of this call, and
* the tool's arguments spread beside them (`e.command` for Bash).
*
* A union discriminated by `tool`: after `if (e.tool === "Bash")`, `e.command`
* is a string and a rewrite is checked against Bash's schema. The `e` of
* `classic.PreToolUse` exactly; `tool.call`'s adds the loop (ToolCallInput).
*/
export type ToolCallEnvelope = BuiltinToolCallInput | McpToolCallInput;
/**
* The input of `tool.call`: the tool, the id of this call, the tool's
* arguments beside them (`e.command` for Bash), and `agentId` in a subagent.
*
* A union discriminated by `tool`: after `if (e.tool === "Bash")`, `e.command`
* is a string and a rewrite is checked against Bash's schema. `tool`,
* `tool_use_id` and `agentId` are reserved: a rewrite of any is refused.
*/
export type ToolCallInput = ToolCallEnvelope & AgentLoop;
/**
* `$.tool.call(input)`: resolves with `result` typed for the tool `input`
* names (ToolCallResult), or loosely for an input that names none literally.
*/
type ToolCallOverloads = {
<T extends string>(input: ToolCallArgs & ToolNamed<T>): Promise<ToolCallResult<T>>;
(input: ToolCallArgs): Promise<ToolCallResult>;
};
/**
* The keys `tool.call`'s input carries beside the tool's own arguments, none
* of which the tool sees (the engine strips them before the tool runs).
*
* `consent` is the person's own words for the press that raised the call
* (`The user pressed "1: Yes" on ...`): the run's context carries it as a human
* turn, which the permission path reads as the user's request.
*/
export type ToolCallReserved<T> = {
tool: T;
tool_use_id?: string;
consent?: string;
};
/**
* What a `tool.call` hook returns and what `next(e)` and `$.tool.call(input)`
* resolve to: the tool's result (`{ result, context? }`) or `{ deny }`.
*
* From core the result is `{ ref, result, text }` or, when the tool reported
* an error, `{ ref, result, text, isError }`; `ref` names core's messages.
*
* @template Name the tool the call went to, typing `result` per built-in
* tool (BuiltinToolResults) once `e.tool` is narrowed; else `unknown`
*/
export type ToolCallResult<Name extends string = string> = {
/**
* Refuses the call: the model receives the text as an error result.
* Absent when the call was answered.
*/
deny: string;
result?: undefined;
context?: undefined;
ref?: undefined;
text?: undefined;
isError?: undefined;
} | {
/**
* The tool's output: from core the tool's record, typed per built-in
* tool once `e.tool` and `isError` are narrowed; from a hook, its own.
*
* Core validates a hook's answer against the tool's output schema when
* it has one, maps it for the model with the tool's own mapper, and
* records it in the transcript as the tool's result. Absent on a deny.
*/
result: ToolResultOf<Name>;
/**
* What the model reads after the tool's result and the user never
* sees. From core, none.
*
* One newline-joined reminder, as a PostToolUse hook's additional
* context is, after the managed tier's review of it; none on a plugin's
* own `$.tool.call`. Kept whole from `next`; capped at 32000 characters.
*/
context?: readonly string[];
/**
* Set by core on what `next(e)` resolves to: names the messages core
* produced for the call (they stay on the host side).
*
* A hook that returns the object it got makes core use them verbatim.
* Absent on a hook's own `{ result }` and on a deny.
*/
ref?: number;
/**
* Set by core: the result as the model reads it (text blocks joined),
* present whatever the tool, where `result`'s shape varies per tool.
*
* Absent on a hook's own `{ result }`.
*/
text?: string;
isError?: undefined;
deny?: undefined;
} | {
/**
* Set by core, present only when the tool reported an error (it threw,
* was interrupted, or answered an error): `text` is what the model read.
*/
isError: true;
/**
* What the transcript stored for the errored call: the error text, or
* undefined when nothing was stored; never the tool's typed record.
*/
result: unknown;
/**
* The error as the model reads it.
*/
text?: string;
/**
* As on an answered result: names the messages core produced.
*/
ref?: number;
/**
* As on an answered result.
*/
context?: readonly string[];
deny?: undefined;
};
/**
* `tool.check`'s input as `$.tool.check` takes it: the tool and its
* arguments; `tool_use_id` is the engine's to set, never a query's.
*/
type ToolCheckArgs = Pick<ToolCheckInput, 'tool' | 'input'>;
/**
* The verdict of `tool.check`: run the tool, put it to the mode's decider
* (the dialog, the auto-mode classifier, a headless host), or refuse it.
*/
type ToolCheckDecision = 'allow' | 'ask' | 'deny';
/**
* The input of `tool.check`: the tool, its arguments, and the call's id when
* the engine is deciding a real call.
*
* All three are the question's identity and are pinned: a hook decides
* about this call, it does not change it (`tool.call` rewrites a call).
*/
type ToolCheckInput = {
/**
* As the model names it (`Bash`, `mcp__server__tool`); the key a matcher
* narrows on.
*/
tool: string;
/**
* The tool's arguments as the permission decision reads them
* (`{ command }` for Bash, `{ file_path, ... }` for the file tools).
*/
input: unknown;
/**
* The call being decided, on a real call only; absent on a query.
*
* `next.origin` names who raised it: `{ plugin: 'engine', tier: 'core' }`
* for the model's own call, the plugin for its `$.tool.call` or its query.
*/
tool_use_id?: string;
};
/**
* What a `tool.check` hook returns and what `next(e)` resolves to: the
* verdict, why, and the settings rule behind it when one decided.
*
* From core, the engine's declarative decision for the session's mode and
* rules. A hook may answer any verdict in either direction; the last word up
* the chain is the decision.
*/
type ToolCheckResult = {
/**
* `allow` runs the tool; `ask` puts it to the mode's decider; `deny`
* refuses it, the reason the model's error.
*/
decision: ToolCheckDecision;
/**
* Why, in a sentence: from core the rule or check that decided; from a
* hook, what the model reads on a deny and the dialog shows on an ask.
*/
reason?: string;
/**
* The settings rule that decided, as written (`Bash(git push:*)`).
*
* Absent for a mode or a tool's own check.
*/
rule?: string;
};
/**
* The input of `tool.describe`: one tool's description, at the moment the
* engine first renders the tool's schema for the model.
*/
export type ToolDescribeInput = {
/**
* As the model sees the name (`Bash`, `mcp__server__tool`); the key a
* matcher narrows on.
*/
tool: string;
/**
* The tool's description as it computed it.
*/
description: string;
/**
* Who provides this tool: the plugin and its tier; `{ plugin: "engine",
* tier: "core" }` for a built-in. Pinned: a rewrite is refused.
*
* A configured MCP server's tool is `mcp:<server>`, in `prepend` when the
* policy settings source configures the server, else `user`.
*/
provider: Origin;
};
/**
* What a `tool.describe` hook returns: the description the model sees for that
* tool.
*/
export type ToolDescribeResult = {
description: string;
};
/**
* `{ tool, tool_use_id, ...args }` as one flat object type, generic over
* the tool name and its parsed arguments.
*/
type ToolEnvelope<Name, Arguments> = {
/**
* The name of the tool being called (`Bash`, `mcp__<server>__<tool>`);
* comparing it narrows `e`. Reserved: a rewrite of it is ignored by core.
*/
tool: Name;
/**
* The tool_use block's id: the same at every event of the call and in
* `$.ui.notice`. Reserved: a rewrite of it is ignored by core.
*/
tool_use_id: string;
} & Arguments;
/**
* One tool call of a ToolGroup, as `ui.render` sees it under `calls`.
*/
export type ToolGroupCall = {
/**
* The id `tool.call` carried for this call (`e.tool_use_id` there), so a
* hook that saw the call finds its row in the group. Read-only.
*
* Absent on a desktop host that predates it.
*/
tool_use_id?: string;
/**
* Which one the call ran (`Bash`, `Read`, `Grep`, ...).
*/
tool: string;
/**
* The call's input, as the model sent it.
*/
input: unknown;
/**
* True while the call is still running.
*/
isRunning: boolean;
/**
* True when the call ended in an error.
*/
isErrored: boolean;
/**
* True when an abort ended the call, as on `ToolUse`.
*/
isInterrupted: boolean;
/**
* As on `ToolUse`; undefined while the call runs.
*/
output?: unknown;
};
/**
* One tool as `$.tool.list()` returns it.
*/
export type ToolInfo = {
/**
* What the model calls it by.
*/
name: string;
/**
* What it does, in the tool's own words (its description; a first sentence at
* most for MCP tools without one).
*/
description: string;
/**
* True for an MCP server's tool.
*/
mcp: boolean;
};
/**
* `{ tool, tool_use_id, ...args }` as one flat object type.
*
* The docs of `tool` and `tool_use_id` live on the `keyof` operand: a mapped
* type takes its properties' docs from there.
*/
export type ToolInputOf<Name extends string, Arguments> = {
[K in keyof ToolEnvelope<Name, Arguments>]: ToolEnvelope<Name, Arguments>[K];
};
/**
* An input that names its tool as the literal `T`: what `next` and
* `$.tool.call` read to type the call's result per tool (NextResultFor).
*/
type ToolNamed<T extends string> = {
/**
* The name of the tool being called (`Bash`).
*/
readonly tool: T;
};
/**
* The structured result of the tool named `Name`: its BuiltinToolResults
* entry for a built-in tool, else `unknown`.
*
* Agent's is its entry or an AgentCallRecord (what a plugin-raised call
* answers). `unknown` covers an MCP tool, a name the results table lacks
* (one merged into the inputs table alone too), and `Name` left at `string`.
*/
export type ToolResultOf<Name extends string> = string extends Name ? unknown : Name extends keyof BuiltinToolResults & string ? BuiltinToolResults[Name] | (Name extends 'Agent' ? AgentCallRecord : never) : unknown;
/**
* One tool_result block of a user message.
*/
export type ToolResultSummary = {
/**
* The id of the call this result answers (`tool.call`'s `e.tool_use_id`).
*/
tool_use_id: string;
/**
* The result as the model read it (text blocks joined).
*/
text: string;
/**
* True when the tool reported an error.
*/
isError: boolean;
/**
* What the transcript stored for the call: the tool's record on an answered
* one (`tool.call`'s `result`), the error text when `isError`.
*
* Absent when nothing was stored. Headless (`-p`), a tool may store the
* record less its bulk (Bash blanks `stdout`); `text` is what the model
* read either way.
*/
result?: unknown;
};
/**
* What `$.tool.register` takes.
*/
export type ToolSpec = {
/**
* The tool's short name (letters, digits, `_`, `-`; up to 64); the model
* calls it as `mcp__<plugin>__<name>`.
*/
name: string;
/**
* What the tool does, for the model.
*/
description: string;
/**
* A JSON schema object for the input (`{ type: "object", properties,
* required }`); default `{ type: "object" }`.
*/
inputSchema?: Record<string, unknown>;
};
/**
* One tool_use block of an assistant message, with its outcome once the
* transcript holds the call's tool_result (paired by `tool_use_id`).
*/
export type ToolUseSummary = {
/**
* The call's id, as `tool.call` carried it (`e.tool_use_id` there).
*/
tool_use_id: string;
/**
* Which one was called (`Read`, `Bash`, `mcp__server__tool`), as
* `tool.call` named it (`e.tool` there).
*/
tool: string;
/**
* The arguments the model gave it.
*/
input: Record<string, unknown>;
/**
* What the transcript stored for the call: the tool's record on an answered
* one (`tool.call`'s `result`), the error text on a refused or errored one.
*
* Absent while the call is in flight or when nothing was stored. Headless
* (`-p`), a tool may store the record less its bulk (Bash blanks `stdout`);
* `text` holds either way.
*/
result?: unknown;
/**
* The result as the model read it; absent while the call is in flight.
*/
text?: string;
/**
* Present only when the tool reported an error, as on `tool.call`'s result.
*/
isError?: true;
};
/**
* One settled run of a link beneath the caller, as `next.trace` lists it:
* data, not a handle.
*
* `received` and `returned` are the live references where the hook runs
* beside the chain; in a hooks module its own copies, as `e` is.
*/
export type TraceEntry<N extends EventName = EventName, E = Args<N>, O = NextResult<N>> = {
/**
* The link's place in the chain, 0 the outermost.
*/
readonly index: number;
/**
* The hook's plugin; `"engine"` for the engine's own core or bottom.
*/
readonly plugin: string;
/**
* The link's tier (Tier); `"core"` for the engine's own core or bottom.
*/
readonly tier: Tier;
readonly event: N;
readonly outcome: TraceOutcome;
/**
* Why the link was skipped without running, when it was: `bypassed by
* <plugin>`, whose `next.to` went beneath this tier. Absent when it ran.
*/
readonly reason?: string;
/**
* Its own wall time, its `next()` calls' time in flight taken out.
*
* The engine entry's is everything beneath the last hook: in a hooks
* module, the host round trip.
*/
readonly ms: number;
/**
* How many chunks the link yielded up, on a streaming event; absent on
* every other. A link left mid-stream counts what it yielded before.
*/
readonly chunks?: number;
readonly received: E;
/**
* What the link settled on; undefined when it was skipped or rejected.
*/
readonly returned: O | undefined;
};
/**
* What the chain decided for one link, as `next.trace` names it.
*
* `returned`: its result stood; `passed`: it returned, by reference, what its
* last `next()` resolved to (a hooks module's hook answers with a copy of its
* own, so it reads `returned`); `skipped`: it failed before `next`, or a
* `next.to` above continued beneath its tier (`reason` says which), and
* beneath ran in its place; `kept`: it failed after `next`, and that run's
* result stands; `expired`: its budget ran out (what stands follows
* skipped/kept); `caught`: it threw or its budget ran out, and its `.catch`
* handler's result stands; `rejected`: the link rejected; the deepest such
* entry is where the rejection came from, and the ones above it let it pass.
*/
export type TraceOutcome = 'caught' | 'expired' | 'kept' | 'passed' | 'rejected' | 'returned' | 'skipped';
/**
* What every `turn.complete` carries whatever its reason: the answer, the
* duration, the interrupt flag, the turn's id, its loop and what it cost.
*/
type TurnCompleteFields = {
/**
* The assistant's final visible text this turn ("" if none, e.g.
* thinking-only).
*/
answer: string;
/**
* Wall-clock length of the turn in milliseconds.
*/
durationMs: number;
/**
* True when the turn ended by interruption (`reason === 'aborted'`).
*/
isAborted: boolean;
/**
* The turn's id, the same one its `turn.start` and every `turn.step`
* carried; a subagent's run raises no `turn.start`, its steps carry it.
*/
turnId: string;
/**
* The loop the turn ran in: a subagent's id, as `$.agent.spawn` resolves
* it, each run of its loop one turn; absent on the main loop.
*
* Pinned: a different value is refused, one left out is kept. Every hook
* sees a subagent's turn, so a hook that spawns sees its children's turns
* too and bounds itself.
*/
agentId?: string;
/**
* What the turn cost: its responses' token counts summed and the model of
* the last, read off the API responses the engine already holds.
*
* Absent when the turn got no response (interrupted before one, an API
* error).
*/
usage?: TurnUsage;
};
/**
* The input of `turn.complete`: the assistant's final message of a turn, at
* the moment the turn ends (where the turn's duration is reported).
*
* `reason` says why it ended; `refusal` exists on a refusal alone.
*/
export type TurnCompleteInput = TurnCompleteFields & (TurnCompleteRefused | TurnCompleteUnrefused);
/**
* Why a turn ended: the model answered, the user interrupted it, the model
* refused with no fallback model to retry on, or an API error ended it.
*/
export type TurnCompleteReason = 'answer' | 'aborted' | 'refusal' | 'error';
/**
* The end of a turn the model refused with no fallback model to retry on:
* what the API said of the refusal rides along.
*/
type TurnCompleteRefused = {
reason: 'refusal';
refusal: TurnRefusal;
};
/**
* What a `turn.complete` hook returns and what `next(e)` resolves to:
* `{ text }`; a text other than a main-loop answer's is shown beneath it.
*
* Core fills `usage` from `e.usage` when the turn had one; a hook above reads
* it, and one that answers its own may leave it out.
*/
export type TurnCompleteResult = {
text: string;
usage?: TurnUsage;
};
/**
* The end of a turn that was not a refusal: answered, interrupted, or dead
* on an API error (retries exhausted, the context limit), nothing more.
*/
type TurnCompleteUnrefused = {
reason: Exclude<TurnCompleteReason, 'refusal'>;
};
/**
* What the API said about a refusal that ended a turn: the classifier's
* category and its explanation, each null when the API sent none.
*/
export type TurnRefusal = {
category: string | null;
explanation: string | null;
};
/**
* The input of `turn.start`: the prompt a model turn begins with, after
* `prompt.submit` settled the text and the UserPromptSubmit settings hooks ran.
*/
export type TurnStartInput = {
/**
* The user's text as the turn proceeds with it ("" for a turn started without
* a typed prompt, e.g. a continuation).
*/
text: string;
/**
* The turn's id, minted here; the same one every `turn.step` and the
* `turn.complete` of this turn carry.
*/
turnId: string;
};
/**
* What a `turn.start` hook returns and what `next(e)` resolves to:
* `{ turnId }`, echoed by core; a hook's own value does not change the turn.
*/
export type TurnStartResult = {
turnId: string;
};
/**
* One piece of a `turn.step` response as it streams through the chain:
* what a hook's `next(e)` yields and what the hook yields up in turn.
*
* Text, thinking, a tool call's start and arguments, and the stop are
* plain data a hook reads and rewrites; `engine` is the rest, passed on
* unread. What leaves the outermost hook is what is shown and recorded.
*/
export type TurnStepChunk = TurnStepTextChunk | TurnStepThinkingChunk | TurnStepToolChunk | TurnStepInputChunk | TurnStepStopChunk | TurnStepEngineChunk;
/**
* An item of the engine's stream the other chunk kinds do not model (the
* envelope, a block's start and end, a retry marker), opaque by `ref`.
*
* Pass it on where it came. A hook that yields its own response has none
* to yield, and the engine supplies what the response needs around the
* chunks it does yield.
*/
export type TurnStepEngineChunk = {
kind: 'engine';
/**
* The engine's handle on the item; opaque, this step's only.
*/
ref: number;
};
/**
* The input of `turn.step`: one model request inside a turn, at the moment
* the engine is about to send it; the bottom of the chain sends it.
*
* The transcript is not on it: `messageCount` says how many messages the
* request carries, and `$.session.messages()` reads them. A hook rewrites
* `model` or `effort` going down; the rest is pinned.
*/
export type TurnStepInput = {
/**
* The turn this step belongs to (`turn.start`'s id; inside a subagent's
* loop, the id the run's `turn.complete` will carry). Pinned.
*/
turnId: string;
/**
* The step's position in the turn, from 0. Pinned.
*/
index: number;
/**
* Which model the request names, as the engine resolved it for this step
* (the session's, a fallback's). `next({ ...e, model })` names another.
*/
model: string;
/**
* How hard the request asks the model to think: the session's setting or
* the model's default, absent for a model without effort; rewritable.
*/
effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' | number;
/**
* How many messages the request carries (the conversation so far, the
* turn's tool results included). Pinned: the messages are the engine's.
*/
messageCount: number;
/**
* The loop the request is made in: a subagent's id, the `id`
* `$.agent.list()` gives it and its `tool.call`s carry; absent on main.
*
* Pinned: a different value is refused, one left out is kept. A subagent
* a hook spawned through `$.agent.spawn` steps past that hook, as its tool
* calls do; every other hook sees its steps.
*/
agentId?: string;
};
/**
* A piece of a tool call's arguments as they arrive: JSON text, partial,
* for the `tool` chunk of the same `index`.
*
* The arguments the tool runs with are the pieces concatenated and parsed
* once the block ends; pieces that do not parse leave the call without
* arguments it can run on, as a model that wrote broken JSON would.
*/
export type TurnStepInputChunk = ChunkRef & {
kind: 'input';
index: number;
/**
* The next piece of the arguments' JSON text.
*/
json: string;
};
/**
* What a `turn.step` hook returns and what `next(e)` resolves to: the
* model's response to the step's request, once its blocks are all in.
*
* From the bottom, the response the engine streamed; a hook's own value
* changes what the hooks above it read, never what the engine streamed.
*/
export type TurnStepResult = {
/**
* The turn this step belongs to, as received.
*/
turnId: string;
/**
* The step's position in the turn, as received.
*/
index: number;
/**
* The visible text of the response ("" when it only called tools, only
* thought, or no request was made).
*/
answer: string;
/**
* The tool calls the response made, in order; empty for a text-only step.
*/
toolUses: readonly TurnStepToolUse[];
/**
* Why the model stopped; null when no response arrived (the request
* failed or was interrupted before a message, or no request was made).
*/
stopReason: TurnStopReason;
/**
* What the request cost as the API reported it, and the model that
* answered; null when no response arrived or it carried no usage.
*/
usage: TurnUsage | null;
};
/**
* The response is whole: why the model stopped and what the request cost,
* as the step's result will carry them. The last chunk of one response.
*/
export type TurnStepStopChunk = ChunkRef & {
kind: 'stop';
stopReason: TurnStopReason;
usage: TurnUsage | null;
};
/**
* A piece of the response's visible text as it arrives, in block `index`.
*
* The text the person watches stream and the text the transcript records
* are both the concatenation of these, in order, per block: a hook that
* rewrites them rewrites both, one that drops them all drops the block.
*/
export type TurnStepTextChunk = ChunkRef & {
kind: 'text';
/**
* The content block the piece belongs to, from 0 within one response.
*/
index: number;
text: string;
};
/**
* A piece of the model's thinking as it arrives, in block `index`: what
* the person sees of it live.
*
* The thinking block the transcript keeps is the one the model signed, as
* the engine received it; thinking a hook streams without the engine's
* block behind it is shown and not recorded.
*/
export type TurnStepThinkingChunk = ChunkRef & {
kind: 'thinking';
index: number;
text: string;
};
/**
* The model begins a tool call in block `index`: the tool's name and the
* call's id; its arguments follow as `input` chunks of the same index.
*
* A block whose `tool` chunk never comes out of the chain is no tool call:
* the engine records none and runs none.
*/
export type TurnStepToolChunk = ChunkRef & {
kind: 'tool';
index: number;
/**
* The call's `tool_use_id`.
*/
id: string;
/**
* The tool's name (`Read`, `Bash`, `mcp__server__tool`).
*/
name: string;
};
/**
* One tool call the model asked for in a step: the tool's name and its
* arguments.
*/
export type TurnStepToolUse = {
/**
* The tool's name (`Read`, `Bash`, `mcp__server__tool`).
*/
name: string;
/**
* The arguments the model gave it, as the tool schema shapes them.
*/
input: unknown;
};
/**
* Why the model stopped, as a `turn.step` result and its stop chunk carry
* it: one of the API's stop reasons, or null when no response arrived.
*/
type TurnStopReason = 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | 'pause_turn' | 'compaction' | 'refusal' | 'model_context_window_exceeded' | null;
/**
* What a model turn, or one response inside it, cost as the API reported it:
* the four token counts (`$.model.fork`'s usage shape) and the model's id.
*
* A turn's counts are its responses' summed; its model is the last response's.
*/
export type TurnUsage = ModelForkUsage & {
/**
* Which model answered, by the id the API reports.
*/
model: string;
};
/**
* What a plugin's `$.ui.blit(args)` takes: which of its mounted Rasters to
* repaint, in which of its sites, and the cells to paint it with.
*
* The Raster is one this plugin's own `ui.render` hook drew, still mounted;
* `columns` and `rows`, when given, must be the mounted size (a resize is a
* redraw, `$.ui.invalidate("ui.render")`, not a blit).
*/
export type UiBlitArgs = {
/**
* The site the Raster is drawn in, by the `requestId` this plugin draws
* it under: one of its panes' ids, a tool row's `tool_use_id`, the band's.
*/
requestId: string;
/**
* The Raster's `key` in that drawing.
*/
key: string;
/**
* The new cells, encoded as the element's `cells` are (RasterProps), for
* the mounted `columns * rows`.
*/
cells: string;
/**
* The width the cells are laid out for; refused unless it is the mounted
* Raster's. Absent, the mounted width.
*/
columns?: number;
/**
* The height the cells are laid out for; refused unless it is the mounted
* Raster's. Absent, the mounted height.
*/
rows?: number;
};
/**
* What `$.ui.blit` resolves to and what a `ui.blit` hook's `{ value }`
* holds: `{}` once the cells are the Raster's next frame, or why not.
*/
export type UiBlitResult = {
/**
* Absent when the cells were taken; else why not: nothing of this plugin's
* is mounted there, the size is not the mounted one, the cells are bad.
*
* Another plugin's Raster under the same site and key reads as not this
* plugin's; a cell that does not decode is named by its index.
*/
deny?: string;
};
/**
* What a plugin's `$.ui.focus(args)` takes: one of its own elements, by the
* `key` it drew it under, in one of its sites that holds the keyboard now.
*
* The engine resolves it to that site's ring and raises `ui.focus` under
* the plugin's origin; the keyboard is the person's to give, so a site that
* does not hold it, or holds it on another plugin's element, is `{ deny }`.
*/
export type UiFocusArgs = {
/**
* The site, by the `requestId` this plugin draws it under: one of its
* panes' ids, or the band's.
*/
requestId: string;
/**
* The element's `key`: a `Button`, `Input` or `Select` this plugin drew in
* that site; of several under one key, the first in document order.
*/
key: string;
};
/**
* The render components whose site keeps a focus ring: a pane's body and
* the band above the prompt, each a ring over the elements hooks drew there.
*/
export type UiFocusComponent = 'Pane' | 'AbovePrompt';
/**
* The input of `ui.focus`: a site's focus ring about to move onto one of the
* elements a hook drew in it (a `Button`, `Input` or `Select`), or off them.
*
* Every key but `element` is the engine's word, pinned: `next(e)` passes
* them on, a rewrite that leaves one out keeps it, one that changes it fails
* the hook. `element` is the hook's to rewrite; the ring has not moved yet.
*/
export type UiFocusInput = {
/**
* Which site: a `Pane` body or the `AbovePrompt` band.
*/
component: UiFocusComponent;
/**
* The instance the `ui.render` hook drawing the site sees: the pane's id,
* or the band's one id.
*/
requestId: string;
/**
* Whose `ui.render` hook drew the element taking the ring; absent with
* `element`. Read-only.
*/
plugin?: string;
/**
* The `key` of the element taking the ring, as `ui.press` names it; absent
* for one of the engine's own stops (a pane's close mark or another's tab).
*
* `next({ ...e, element })` lands it on another element `plugin` drew in
* the site instead; one not drawn there is core's `{ deny }`.
*/
element?: string;
/**
* Who moves it (UiFocusOrigin), set by the engine where the move starts.
*/
origin: UiFocusOrigin;
};
/**
* Who moves the ring at `ui.focus`, as the engine stamps it where the move
* starts; a closed set a matcher narrows on.
*
* `next(e)` passes it on as received; no hook sets one.
*/
export type UiFocusOrigin = {
/**
* The person, by Tab, the arrows or a click while the site holds the
* keyboard.
*/
kind: 'person';
} | {
/**
* A plugin's `$.ui.focus`, or its `autoFocus` element taking the ring
* as the site takes the keyboard.
*/
kind: 'plugin';
/**
* The focusing plugin's name.
*/
name: string;
};
/**
* What a `ui.focus` hook returns, what `next(e)` resolves to, and what
* `$.ui.focus` hands back: `{}` once the ring moved, or why it did not.
*
* As `ui.scroll` spells it.
*/
export type UiFocusResult = {
/**
* Absent when the ring is where the chain left it; else why nothing
* moved.
*
* A hook kept the ring (no `next`); the site is not this plugin's, does
* not hold the keyboard, or another plugin's element holds it; no element
* of `plugin` is drawn under `element`; another move landed first.
*/
deny?: string;
};
/**
* The argument of `ui.input`: a change of, or a submit from, an `Input` a
* render hook drew. Flat and frozen like every event's.
*
* Another plugin addresses one field by matcher:
* `on("ui.input", { plugin: "roster", element: "reply" }, ...)`.
*/
export type UiInputArgument = {
/**
* Whose `ui.render` hook drew the element.
*/
plugin: string;
/**
* The `key` the hook gave its `Input`: its address, what a matcher names.
*/
element: string;
/**
* The render component the element was drawn in (`AbovePrompt`,
* `ToolUse`, ...).
*/
component: RenderComponent;
/**
* The instance the element was drawn in: the `requestId` the `ui.render`
* hook that drew it saw (a tool row's tool_use_id, a pane's id).
*/
requestId: string;
/**
* Where the typing came from, one literal per member, so
* `if (e.surface === "terminal")` narrows `e`.
*/
surface: RenderSurface;
/**
* `change` after every edit of the text; `submit` on Enter.
*/
kind: 'change' | 'submit';
/**
* The field's whole text at that moment; a hook above may rewrite it for
* the plugins beneath and the element's own handler.
*/
value: string;
};
/**
* What a `ui.input` hook returns and what `next(e)` resolves to.
*
* Beneath every hook, core runs the element's `onInput` (kind `change`) or
* `onSubmit` (kind `submit`) closure in its plugin's environment with the
* value as the chain left it, and answers `{ element, value }`.
*/
export type UiInputResult = {
/**
* Which handler the input reached, by its Input's `key`.
*/
element: string;
/**
* The text the handler received.
*/
value: string;
};
/**
* The argument of `ui.message`: what a `Client` instance's surface module
* posted (`surface.post(data)`), addressed by where the instance is drawn.
*
* The origin is `client`: code sent it, on nobody's behalf, so `data` is
* input to validate, not a fact. Everything but `data` is the engine's word
* and a hook may not rewrite it.
*/
export type UiMessageArgument = {
/**
* Where the instance is drawn: `terminal`, or `desktop` once it has them.
*/
surface: RenderSurface;
/**
* The render component the `Client` was drawn in (`AbovePrompt`, `Pane`,
* ...).
*/
component: RenderComponent;
/**
* The engine's id for the drawing the `Client` sits in: the `requestId` the
* `ui.render` hook that drew it saw.
*/
requestId: string;
/**
* The `Client`'s `key`: which instance posted.
*/
element: string;
/**
* The `Client`'s `module`: which surface module runs there, as its path
* under the plugin's folder.
*/
module: string;
/**
* What the instance posted: plain data (JsonValue), bounded as a tree's
* text is; typed `unknown` since it came from code. Rewritable.
*/
data: unknown;
};
/**
* What a `ui.message` hook returns and what `next(e)` resolves to.
*
* Core answers `{}`: the message was heard and nothing changes. A hook that
* answers `{ props }` hands the posting instance its next props directly, its
* local state kept, with no `ui.render` run; the plugin's next redraw hands
* props again as usual.
*/
export type UiMessageResult = {
/**
* The instance's next props, plain data (JsonValue) bounded as a `Client`'s
* props are; absent leaves the instance's props as they were.
*/
props?: unknown;
};
/**
* The argument of `ui.press`: a press on a `Button` a render hook drew.
* Flat and frozen like every event's.
*
* Another plugin addresses one button by matcher:
* `on("ui.press", { plugin: "explainer", element: "explain" }, ...)`.
*/
export type UiPressArgument = {
/**
* Whose `ui.render` hook drew the element.
*/
plugin: string;
/**
* The `key` the hook gave its `Button`: its address, what a matcher names.
*/
element: string;
/**
* The render component the element was drawn in (`ToolUse`,
* `AssistantMessage`, ...).
*/
component: RenderComponent;
/**
* The instance the element was drawn in: the `requestId` the `ui.render`
* hook that drew it saw (a tool row's tool_use_id, a pane's id).
*/
requestId: string;
/**
* Where the press came from, one literal per member, so
* `if (e.surface === "terminal")` narrows `e`.
*/
surface: RenderSurface;
};
/**
* What a `ui.press` hook returns and what `next(e)` resolves to.
*
* Beneath every hook, core runs the element's `onPress` closure in its
* plugin's environment with `e` as the chain left it, and answers
* `{ element }`.
*/
export type UiPressResult = {
/**
* Which handler the press reached, by its Button's `key`.
*/
element: string;
};
/**
* What a plugin's `$.ui.scroll(args)` takes: what to bring into view, in
* which of its sites, and where in the window it lands.
*
* The engine resolves it to a window and an offset and raises `ui.scroll`
* under the plugin's origin; a transcript row is the person's to move, so
* it is revealed only while the plugin answers the person's own input.
*/
export type UiScrollArgs = {
/**
* What to reveal (UiScrollTarget): a render instance by `requestId`, one
* of this plugin's elements by `key`, or the `start` or `end` of `in`.
*/
to: UiScrollTarget;
/**
* The site to scroll, by the `requestId` this plugin draws it under: one
* of its panes' ids, or the band's.
*
* Required with `start` and `end`; with `{ key }` it picks the site when
* the key is drawn in several.
*/
in?: string;
/**
* Where the target lands in the window (UiScrollBlock); `nearest` when
* left out, so a row already showing does not move.
*/
block?: UiScrollBlock;
};
/**
* Where in its scrollable a revealed row lands, as the DOM's
* `scrollIntoView({ block })` names it.
*
* `nearest` moves the least that shows the row whole, and not at all when
* it already shows; `start`, `center` and `end` put its top, middle or
* bottom at that edge of the window. A row taller than the window shows
* its top.
*/
export type UiScrollBlock = 'start' | 'center' | 'end' | 'nearest';
/**
* The render components whose site the engine scrolls: a pane's body and
* the band above the prompt, each a window over the tree a hook drew there.
*/
export type UiScrollComponent = 'Pane' | 'AbovePrompt';
/**
* The input of `ui.scroll`: a site's window asked to move over the tree a
* hook drew in it (a pane's body, the band above the prompt).
*
* Every key but `offset` is the engine's word, pinned: `next(e)` passes
* them on, a rewrite that leaves one out keeps it, one that changes or adds
* one fails the hook. `offset` is the hook's to rewrite; nothing moved yet.
*/
export type UiScrollInput = {
/**
* Which site: a `Pane` body or the `AbovePrompt` band.
*/
component: UiScrollComponent;
/**
* The instance the `ui.render` hook drawing the site sees: the pane's id,
* or the band's one id.
*/
requestId: string;
/**
* The first row the window is to show, 0 at the top: the row it shows
* now plus `by`, clamped to the tree, or where `$.ui.scroll` resolved.
*
* `next({ ...e, offset })` moves it elsewhere (a clamp); one past the
* tree's end lands at the end. Nothing has moved when a hook reads it.
*/
offset: number;
/**
* The rows the move asks for, signed, negative toward the top; what the
* DOM's `scrollBy` takes. Read-only.
*
* The person's: a wheel tick `-1` or `1` at rest, more as ticks crowd or
* summed in flight; an arrow a row while the engine has rows to scroll, a
* page key `bodyRows`, Home and End `contentRows`. A plugin's: its distance.
*/
by: number;
/**
* How many rows of the tree the window shows at once, as drawn now.
* Read-only.
*/
bodyRows: number;
/**
* How many rows the tree has, as drawn now: the window's last offset is
* `contentRows - bodyRows`, none when the tree fits. Read-only.
*/
contentRows: number;
/**
* Who moves it (UiScrollOrigin), set by the engine where the move starts.
*/
origin: UiScrollOrigin;
/**
* The body cell the person's wheel or trackpad was over (UiScrollPointer);
* absent for the scroll keys and for `$.ui.scroll`. Read-only.
*
* Moves summed while a dispatch was in flight carry the latest one's. A
* hook pinning a list over rows it scrolls itself tells a tick over the
* list (`row` among its list's rows) from one over the body.
*/
pointer?: UiScrollPointer;
};
/**
* Who moves the window at `ui.scroll`, as the engine stamps it where the
* move starts; a closed set a matcher narrows on.
*
* `next(e)` passes it on as received; no hook sets one.
*/
export type UiScrollOrigin = {
/**
* The person, by the wheel over the site or its scroll keys while
* they hold it.
*/
kind: 'person';
} | {
/**
* A plugin's `$.ui.scroll`.
*/
kind: 'plugin';
/**
* The scrolling plugin's name.
*/
name: string;
};
/**
* The cell the pointer was over when the person's wheel raised `ui.scroll`,
* in the site's body: the box its `ui.render` hook draws into, as painted.
*
* The DOM's `clientY - body.top` in cells, the window's offset not added: a
* hook drawing its own window reads `row` as its tree's row, one the engine
* scrolls adds the `scroll.offset` it drew with. The frame lies outside.
*/
export type UiScrollPointer = {
/**
* 0 at the body's left edge, as `bodyColumns` counts them; negative, or
* `bodyColumns` and past, over an inline pane's side borders.
*/
column: number;
/**
* 0 at the body's first showing row, as `bodyRows` counts them.
*
* The tree's row is `scroll.offset + row` under the engine's window, and
* `row` itself under a hook's own (offset 0); negative over a pane's top
* border or tab row, `bodyRows` or more over its bottom border.
*/
row: number;
};
/**
* What a `ui.scroll` hook returns, what `next(e)` resolves to, and what
* `$.ui.scroll` hands back: `{}` once the window moved, or why it did not.
*/
export type UiScrollResult = {
/**
* Absent when the window is where the chain left it; else why nothing
* moved, as `tool.call` and `config.set` spell a refusal.
*
* A hook kept the window (no `next`); the target is not this plugin's;
* another move landed first (`the window moved meanwhile`); a transcript
* row is not the person's ask (`not person-initiated`) or none scrolls.
*/
deny?: string;
};
/**
* What `$.ui.scroll` brings into view: never a row number, always a thing
* drawn somewhere.
*
* `{ requestId }` names a render instance by the id its `ui.render` hook
* saw (a transcript message's, a tool row's tool_use_id), scrolled into view
* inside whatever scrolls it. `{ key }` names an element this plugin drew
* with that `key`, inside the site it drew it in. `start` and `end` are the
* top and bottom of the site `in` names; `end` keeps up with a tree that
* grows (rows the plugin just added count) until anything next moves it.
*/
export type UiScrollTarget = {
requestId: string;
} | {
key: string;
} | 'start' | 'end';
/**
* The argument of `ui.select`: a pick from a `Select` a render hook drew.
* Flat and frozen like every event's.
*
* Another plugin addresses one picker by matcher:
* `on("ui.select", { plugin: "roster", element: "peer" }, ...)`.
*/
export type UiSelectArgument = {
/**
* Whose `ui.render` hook drew the element.
*/
plugin: string;
/**
* The `key` the hook gave its `Select`: its address, what a matcher names.
*/
element: string;
/**
* The render component the element was drawn in (`AbovePrompt`,
* `ToolUse`, ...).
*/
component: RenderComponent;
/**
* The instance the element was drawn in: the `requestId` the `ui.render`
* hook that drew it saw (a tool row's tool_use_id, a pane's id).
*/
requestId: string;
/**
* Where the pick came from, one literal per member, so
* `if (e.surface === "terminal")` narrows `e`.
*/
surface: RenderSurface;
/**
* The picked option's value; a hook above may rewrite it for the plugins
* beneath and the element's own handler.
*/
value: string;
};
/**
* What a `ui.select` hook returns and what `next(e)` resolves to.
*
* Beneath every hook, core runs the element's `onSelect` closure in its
* plugin's environment with the value as the chain left it, and answers
* `{ element, value }`.
*/
export type UiSelectResult = {
/**
* Which handler the pick reached, by its Select's `key`.
*/
element: string;
/**
* What the handler received: the option's value as the chain left it.
*/
value: string;
};
/**
* The intersection of a union's members (`A | B` to `A & B`), by inferring
* one parameter type from the contravariant positions.
*/
type UnionToIntersection<U> = (U extends unknown ? (member: U) => void : never) extends (member: infer I) => void ? I : never;
type UserPromptExpansionHookInput = BaseHookInput & {
hook_event_name: 'UserPromptExpansion';
expansion_type: 'slash_command' | 'mcp_prompt';
command_name: string;
command_args: string;
command_source?: string;
prompt: string;
};
type UserPromptSubmitHookInput = BaseHookInput & {
hook_event_name: 'UserPromptSubmit';
prompt: string;
/**
* Who authored/injected the prompt: `user` = submitted from the interactive composer, `sdk` = non-interactive entrypoint (`-p` / Agent SDK), `loop_wakeup` = dynamic /loop wakeup, `schedule_wakeup` = scheduled-task fire (CronCreate/routine), `system` = other machine-injected turns (peer/channel messages, task notifications, auto-continuation), `poll_event` = the poll-event channel enqueue-time pass (the hook fires when the host submits an event, before its delivery ack exists - a blocking verdict rejects the event). Payloads may omit it while the field rolls out.
*/
source?: 'user' | 'sdk' | 'system' | 'loop_wakeup' | 'schedule_wakeup' | 'poll_event';
session_title?: string;
};
/**
* The result of a call on `$` as the hooks on its event see it: `{ value }`,
* the call's answer, or `{ deny }`, the reason the caller's promise rejects.
*/
type ValueOrDeny<Value> = {
value: Value;
deny?: undefined;
} | {
deny: string;
value?: undefined;
};
type WorktreeCreateHookInput = BaseHookInput & {
hook_event_name: 'WorktreeCreate';
name: string;
};
type WorktreeRemoveHookInput = BaseHookInput & {
hook_event_name: 'WorktreeRemove';
worktree_path: string;
};
/**
* The globals of a hooks module's environment: these and no others (no DOM,
* no Node).
*/
global {
/**
* The JSX factory (classic runtime, `@jsx h`; the engine prepends the
* pragma): a plain-data element from a string tag or a component.
*/
const h: (
tag: string | ((props: never) => RenderNode | null | undefined),
props: Record<string, unknown> | null | undefined,
...children: unknown[]
) => RenderNode | null | undefined
/**
* `<>...</>`: a column Box around the children.
*/
const Fragment: (props: { children?: RenderNode[] }) => RenderElement
/**
* JSX over the element table: every tag is a constructor from
* `$.ui.resolve(e)` (`const { Box, Text } = $.ui.resolve(e)`), typed by
* its props; there are no intrinsic (string) tags.
*/
namespace JSX {
type Element = RenderElement
type Children = RenderChildren
type ElementType = (props: never) => RenderNode | null | undefined
interface IntrinsicElements {}
interface ElementChildrenAttribute {
children: unknown
}
interface IntrinsicAttributes {
key?: string
}
}
interface AbortSignal {
readonly aborted: boolean
readonly reason: unknown
throwIfAborted(): void
addEventListener(
type: 'abort',
listener: () => void,
options?: { once?: boolean },
): void
removeEventListener(type: 'abort', listener: () => void): void
}
var AbortSignal: {
prototype: AbortSignal
abort(reason?: unknown): AbortSignal
timeout(milliseconds: number): AbortSignal
any(signals: AbortSignal[]): AbortSignal
}
interface AbortController {
readonly signal: AbortSignal
abort(reason?: unknown): void
}
var AbortController: {
prototype: AbortController
new (): AbortController
}
interface TextEncoder {
readonly encoding: string
encode(input?: string): Uint8Array
}
var TextEncoder: { prototype: TextEncoder; new (): TextEncoder }
interface TextDecoder {
readonly encoding: string
decode(input?: ArrayBufferView | ArrayBuffer): string
}
var TextDecoder: { prototype: TextDecoder; new (label?: string): TextDecoder }
interface URLSearchParams {
append(name: string, value: string): void
delete(name: string): void
get(name: string): string | null
getAll(name: string): string[]
has(name: string): boolean
set(name: string, value: string): void
toString(): string
forEach(callback: (value: string, key: string) => void): void
}
var URLSearchParams: {
prototype: URLSearchParams
new (init?: string | Record<string, string> | string[][]): URLSearchParams
}
interface URL {
hash: string
host: string
hostname: string
href: string
readonly origin: string
password: string
pathname: string
port: string
protocol: string
search: string
readonly searchParams: URLSearchParams
username: string
toString(): string
toJSON(): string
}
var URL: {
prototype: URL
new (url: string, base?: string | URL): URL
canParse(url: string, base?: string): boolean
}
function atob(data: string): string
function btoa(data: string): string
function structuredClone<T>(value: T): T
var crypto: {
readonly subtle: {
digest(
algorithm: string | { name: string },
data: ArrayBufferView | ArrayBuffer,
): Promise<ArrayBuffer>
}
randomUUID(): string
getRandomValues<T extends ArrayBufferView>(array: T): T
}
var performance: { now(): number }
}
}
declare module 'claude-code/testing' {
import type { Args } from 'claude-code';
import type { Chunk } from 'claude-code';
import type { EventCalls } from 'claude-code';
import type { EventName } from 'claude-code';
import type { HookStream } from 'claude-code';
import type { On } from 'claude-code';
import type { Register } from 'claude-code';
import type { ResultOf } from 'claude-code';
import type { StreamingEventName } from 'claude-code';
import type { Tier } from 'claude-code';
import type { UiPressResult } from 'claude-code';
/**
* A value that matches by a rule inside `toEqual` and its kin
* (`expect.any`, `expect.objectContaining`), known by its text in a failure.
*/
export type AsymmetricMatcher = {
readonly text: string;
};
/**
* The same checks on what a promise received settles with, each resolving
* once the promise has settled and the check passed.
*/
export type AsyncMatchers = {
[K in keyof Matchers]: (...args: Parameters<Matchers[K]>) => Promise<void>;
};
/**
* A class, as `toThrow`, `toBeInstanceOf` and `expect.any` take it.
*/
export type Constructor = abstract new (...args: never[]) => unknown;
/**
* A group of tests: its name leads the title of each test declared inside,
* and its body runs at once, while the file loads.
*
* @param name the group's name
* @param body declares the group's tests
*/
export const describe: (name: string, body: () => void) => void;
/**
* What a test holds as `$`, the engine's own: every call on it is made as
* the REPL, the query loop and the render sites make theirs, over every plugin.
*
* `next.origin` is the engine, and the whole chain runs over the plugins
* loaded. A tool call's `tool_use_id` is minted when left out, as the engine
* mints it; `$.ui.press` is the terminal pressing a Button a test rendered.
*/
export type Engine = {
[N in keyof EventCalls]: N extends 'ui' ? EngineNoun<N> & EnginePress : EngineNoun<N>;
};
/**
* One call on the engine's `$`: the event's input whole, as an engine call
* site passes it, to its result, or for a streaming event to its stream.
*/
export type EngineCall<E extends EventName> = E extends StreamingEventName ? (e: Args<E>) => HookStream<Chunk<E>, ResultOf[E]> : (e: Args<E>) => Promise<ResultOf[E]>;
/**
* One noun of the engine's `$`: each of its events as the engine calls it,
* `tool.call` and `ui.render` typed per tool and component, `ui.resolve` out.
*/
export type EngineNoun<N extends keyof EventCalls> = {
[V in EngineNounEvent<N>]: `${N}.${V}` extends 'tool.call' | 'ui.render' ? EventCalls[N][V] : EngineCall<`${N}.${V}` & EventName>;
};
/**
* The events of one noun a test's `$` carries: every one but `ui.resolve`,
* which a render hook calls on its own `$` and the engine never raises.
*/
export type EngineNounEvent<N extends keyof EventCalls> = Exclude<keyof EventCalls[N] & string, `${N}.resolve` extends 'ui.resolve' ? 'resolve' : never>;
/**
* The terminal pressing a Button a test rendered: the `ui.press` chain over
* every plugin hooked on it, the Button's own `onPress` at the bottom.
*/
export type EnginePress = {
/**
* Presses the Button, as a click or its hotkey does.
*
* @param target whose Button, its key, and the instance when several
* @returns what the chain settled on; rejects when no such Button is
* drawn on the terminal, or several are and no instance is named
*/
press: (target: PressTarget) => Promise<UiPressResult | undefined>;
};
/**
* The checks on a value (`expect(received)`), and with them the matchers
* that stand inside an expected value (`expect.any(Number)`).
*/
export type Expect = Expecting & Matching;
/**
* Checks a value: `expect(received).toEqual(expected)` throws an
* AssertionError naming both sides when it fails, a message given leading.
*
* `.not` negates; `.resolves` and `.rejects` check what a promise settles
* with; `expect.any(Number)` and its kin stand inside an expected value.
*/
export const expect: Expect;
/**
* What `expect(received)` answers: the checks, their negation, and the
* checks on what a promise received resolves or rejects with.
*/
export type Expectation = Negatable<Matchers> & {
/**
* The checks on what the promise received resolves with; a rejection
* fails them.
*/
resolves: Negatable<AsyncMatchers>;
/**
* The checks on what the promise received rejects with; a resolution
* fails them.
*/
rejects: Negatable<AsyncMatchers>;
};
/**
* `expect(received, message?)`: the checks on a value, a message of the
* test's own leading a failure's.
*/
export type Expecting = (received: unknown, message?: string) => Expectation;
/**
* The checks `expect(received)` offers; each throws an AssertionError when
* it fails, naming what was expected and what was received.
*/
export type Matchers = {
/**
* Passes when received is the value, by `Object.is`.
*
* @param expected the value
*/
toBe: (expected: unknown) => void;
/**
* Passes when received equals the value in structure, properties holding
* undefined ignored; `expect.any` and its kin match inside it.
*
* @param expected the value
*/
toEqual: (expected: unknown) => void;
/**
* As `toEqual`, but undefined properties and prototypes count.
*
* @param expected the value
*/
toStrictEqual: (expected: unknown) => void;
/**
* Passes when received holds at least the object's properties, equal.
*
* @param expected the object
*/
toMatchObject: (expected: object) => void;
/**
* Passes when a string received includes the item, or an iterable
* received has an element that is it.
*
* @param item the substring or element
*/
toContain: (item: unknown) => void;
/**
* Passes when an iterable received has an element equal to the item.
*
* @param item the element
*/
toContainEqual: (item: unknown) => void;
/**
* Passes when received's `length` is the number.
*
* @param length the number
*/
toHaveLength: (length: number) => void;
/**
* Passes when received holds a property at the path (`a.b`, or the keys
* in order), equal to the value when one is given.
*
* @param path the property's path
* @param value what it must equal, when given
*/
toHaveProperty: (path: string | readonly string[], value?: unknown) => void;
/**
* Passes when received is undefined.
*/
toBeUndefined: () => void;
/**
* Passes when received is anything but undefined.
*/
toBeDefined: () => void;
/**
* Passes when received is null.
*/
toBeNull: () => void;
/**
* Passes when received is truthy.
*/
toBeTruthy: () => void;
/**
* Passes when received is falsy.
*/
toBeFalsy: () => void;
/**
* Passes when received is NaN.
*/
toBeNaN: () => void;
/**
* Passes when received is greater than the bound.
*
* @param bound the bound
*/
toBeGreaterThan: (bound: number | bigint) => void;
/**
* Passes when received is the bound or greater.
*
* @param bound the bound
*/
toBeGreaterThanOrEqual: (bound: number | bigint) => void;
/**
* Passes when received is less than the bound.
*
* @param bound the bound
*/
toBeLessThan: (bound: number | bigint) => void;
/**
* Passes when received is the bound or less.
*
* @param bound the bound
*/
toBeLessThanOrEqual: (bound: number | bigint) => void;
/**
* Passes when a string received includes the text, or the pattern matches
* it.
*
* @param pattern the text or pattern
*/
toMatch: (pattern: string | RegExp) => void;
/**
* Passes when a string received starts with the prefix.
*
* @param prefix the prefix
*/
toStartWith: (prefix: string) => void;
/**
* Passes when a string received ends with the suffix.
*
* @param suffix the suffix
*/
toEndWith: (suffix: string) => void;
/**
* Passes when received is an instance of the class.
*
* @param expected the class
*/
toBeInstanceOf: (expected: Constructor) => void;
/**
* Passes when calling received throws (or, under `rejects`, the rejection
* is) an error as described: by substring, pattern, class or message.
*
* @param expected the description; any throw passes without one
*/
toThrow: (expected?: ThrowExpectation) => void;
};
/**
* The matchers that stand inside an expected value, each matching received
* there by a rule instead of by equality.
*/
export type Matching = {
/**
* Matches any instance of the class, a primitive by its wrapper
* (`expect.any(Number)`).
*
* @param expected the class
* @returns the matcher
*/
any: (expected: Constructor) => AsymmetricMatcher;
/**
* Matches anything but null and undefined.
*
* @returns the matcher
*/
anything: () => AsymmetricMatcher;
/**
* Matches a string that includes the text.
*
* @param text the substring
* @returns the matcher
*/
stringContaining: (text: string) => AsymmetricMatcher;
/**
* Matches a string the pattern matches.
*
* @param pattern the pattern, or the source of one
* @returns the matcher
*/
stringMatching: (pattern: string | RegExp) => AsymmetricMatcher;
/**
* Matches an object holding at least the shape's properties, equal.
*
* @param shape the properties
* @returns the matcher
*/
objectContaining: (shape: object) => AsymmetricMatcher;
/**
* Matches an array holding an element equal to each of the items.
*
* @param items the elements
* @returns the matcher
*/
arrayContaining: (items: readonly unknown[]) => AsymmetricMatcher;
};
/**
* The world beneath the plugins, mocked noun by noun: each member registers
* hooks of the test's on `on`, visible where the test calls it.
*/
export type Mock = {
/**
* Answers `$.clock` from a clock in memory that moves only when the test
* moves it: `clock.now` reads it, and each wait is held.
*
* A held wait resolves when an advance crosses the time it is due, and is
* dropped when its dispatch aborts; one held past a hook's budget (ten
* seconds of real time) is let go, as a hook that overran.
*
* @param on the test's `on`
* @param options where the clock starts (`now`, 0 when not given)
* @returns the clock: its time, and the calls that move it
*/
clock: (on: On, options?: MockClockOptions) => MockClock;
/**
* Answers `$.store` from a store in memory: `get`, `set`, `delete` and
* `keys` over it, as the engine keeps a plugin's own.
*
* @param on the test's `on`
* @param entries what the store holds at the start (nothing when not given)
*/
store: (on: On, entries?: Readonly<Record<string, unknown>>) => void;
/**
* Answers `$.env.get` from a set of variables; one not listed is unset.
*
* @param on the test's `on`
* @param variables the environment the plugins read
*/
env: (on: On, variables: Readonly<Record<string, string>>) => void;
};
/**
* The world beneath the plugins, mocked noun by noun: `mock.clock`,
* `mock.store` and `mock.env`.
*
* Each registers hooks of the test's on the `on` it is handed, visible where
* the test calls it, and answers its noun from memory.
*/
export const mock: Mock;
/**
* The clock `mock.clock` hands back: the time its hooks answer, and the only
* ways it moves.
*/
export type MockClock = {
/**
* The time now, in milliseconds: what `$.clock.now()` resolves beneath the
* plugins.
*
* @returns the time
*/
now: () => number;
/**
* Moves the clock on, resolving each wait due on the way (`$.clock.sleep`,
* `after`, `every`, this clock's `sleep`) in the order it comes due.
*
* The clock reads each wait's time as it resolves, and what one started
* runs before the next resolves.
*
* @param ms how far to move, in milliseconds
* @returns resolves once the clock is there and the event loop settled
*/
advance: (ms: number) => Promise<void>;
/**
* Moves the clock to a time at or past now, as `advance` would.
*
* @param ms the time, in milliseconds
* @returns resolves once the clock is there and the event loop settled
*/
set: (ms: number) => Promise<void>;
/**
* Lets what is already under way run as far as it can without the clock
* moving: every wait due now resolves and the event loop settles.
*
* The same as `advance(0)`; the name for the step between starting a
* dispatch unawaited and looking at what it did.
*
* @returns resolves once the event loop settled, the time where it was
*/
settle: () => Promise<void>;
/**
* Resolves once the clock has moved this far past now: how a hook of the
* test's answers late.
*
* @param ms how far, in milliseconds
* @returns resolves when an advance crosses that time
*/
sleep: (ms: number) => Promise<void>;
};
/**
* Where a mocked clock starts: `now`, in milliseconds (0 when not given).
*/
export type MockClockOptions = {
now?: number;
};
/**
* A set of checks and, under `not`, the same set passing where they fail.
*/
export type Negatable<M> = M & {
/**
* The checks negated.
*/
not: M;
};
/**
* Written inline in a test and loaded as a plugin folder is: its name, the
* tier it loads in (`user` when not given), and its hooks module's `register`.
*
* `register` is written `register(on) { ... }` and is self-contained, as a
* module's is: it closes over nothing of the test file.
*/
export type Plugin = {
name: string;
tier?: PluginTier;
register: Register;
};
/**
* A tier a plugin loads in: every tier but the engine's own.
*/
export type PluginTier = Exclude<Tier, 'core'>;
/**
* What `$.ui.press` takes: the plugin whose `ui.render` hook drew the Button,
* the `key` it gave it, and the instance when it drew one in several.
*/
export type PressTarget = {
plugin: string;
key: string;
requestId?: string;
};
/**
* One test: it passes when its body returns or resolves, and fails when it
* throws, rejects or outlasts its time (5000 ms, or `timeoutMs`).
*
* The body gets the engine's `$` and an `on` whose hooks sit beneath every
* plugin; `plugins` load inline plugins beside the one under test. A failure
* carries what the engine reported meanwhile: each hook it skipped, and why.
*
* @param name the test's name, led in its title by the describes around it
* @param rest the body, `($, on) => ...`, or the options then the body
*/
export const test: (name: string, ...rest: TestRest) => void;
/**
* A test: the engine's `$`, and `on`, a plugin's registrar, whose hooks sit
* beneath every plugin; beneath them the bottom hook throws, naming its event.
*
* The plugins load at the test's first call on `$`, so a test registers its
* hooks before it, as a module registers its own in `register()`.
*/
export type TestBody = ($: Engine, on: On) => unknown;
/**
* What `test` takes beside its name: the inline plugins it loads beside the
* one under test, and how long it may run (5000 ms when not given).
*/
export type TestOptions = {
plugins?: readonly Plugin[];
timeoutMs?: number;
};
/**
* What follows a test's name: its body, or its options then its body.
*/
export type TestRest = readonly [body: TestBody] | readonly [options: TestOptions, body: TestBody];
/**
* What `toThrow` compares the thrown error with: a substring or pattern of
* its message, its class, a value carrying the whole message, or nothing.
*/
export type ThrowExpectation = string | RegExp | Constructor | WithMessage;
/**
* Says which tier the plugin under test loads in, once, at the top of the
* file: `prepend`, `user` (when unsaid), `append` or `builtin`.
*
* @param tier the tier
*/
export const tier: (tier: PluginTier) => void;
/**
* An error-like value `toThrow` compares by its whole message.
*/
export type WithMessage = {
message: string;
};
}
// The inputs of the built-in tools this build has, from each tool's
// input schema. Merges into ToolCallInput (BuiltinToolInputs) so
// `e.tool === "Bash"` narrows to the tool's arguments.
declare module 'claude-code' {
interface BuiltinToolInputs {
Agent: {
/** A short (3-5 word) description of the task */
description: string
/** The task for the agent to perform */
prompt: string
/** The type of specialized agent to use for this task */
subagent_type?: string
/** Optional model override for this agent. Takes precedence over the agent definition's model frontmatter and the configured default subagent model. If omitted, uses the agent definition's model, else the default (inherits from the parent unless a default subagent model is configured). Ignored for subagent_type: "fork" β forks always inherit the parent model. */
model?: "sonnet" | "opus" | "haiku" | "fable"
/** Agents run in the background by default; you will be notified when one completes. Set to false only when your very next action depends on this agent's result and nothing else could usefully happen while it runs β otherwise leave it in the background so the user can hand you other work. */
run_in_background?: boolean
/** Name for the spawned agent. Makes it addressable via SendMessage({to: name}) while running. */
name?: string
/** Deprecated; ignored. The session has a single implicit team. */
team_name?: string
/** Deprecated; ignored. Subagents inherit the parent session's permission mode; agent-definition frontmatter may override it. */
mode?: "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan"
/** Isolation mode. "worktree" creates a temporary git worktree so the agent works on an isolated copy of the repo. "remote" launches the agent in a remote cloud environment (always runs in background; availability is gated). */
isolation?: "worktree" | "remote"
}
Bash: {
/** The command to execute */
command: string
/** Optional timeout in milliseconds (max 600000) */
timeout?: number
/** Clear, concise description of what this command does in active voice. Never use words like "complex" or "risk" in the description - just describe what it does. Say what the command does in plain words: do not echo the command's text, its flags, or file paths - the user reads this description, often without seeing the command. For simple commands (git, npm, standard CLI tools), keep it brief (5-10 words): - ls β "List files in current directory" - git status β "Show working tree status" - npm install β "Install package dependencies" For commands that are harder to parse at a glance (piped commands, obscure flags, etc.), add enough context to clarify what it does: - find . -name "*.tmp" -exec rm {} \; β "Find and delete all .tmp files recursively" - git reset --hard origin/main β "Discard all local changes and match remote main" - curl -s url | jq '.data[]' β "Fetch JSON from URL and extract data array elements" */
description?: string
/** Set to true to run this command in the background. */
run_in_background?: boolean
/** Set this to true to dangerously override sandbox mode and run commands without sandboxing. */
dangerouslyDisableSandbox?: boolean
}
CronCreate: {
/** Standard 5-field cron expression in local time: "M H DoM Mon DoW" (e.g. "* /5 * * * *" = every 5 minutes, "30 14 28 2 *" = Feb 28 at 2:30pm local once). */
cron: string
/** The prompt to enqueue at each fire time. */
prompt: string
/** true (default) = fire on every cron match until deleted or auto-expired after 7 days. false = fire once at the next match, then auto-delete. Use false for "remind me at X" one-shot requests with pinned minute/hour/dom/month. */
recurring?: boolean
/** true = persist to .claude/scheduled_tasks.json and survive restarts. false (default) = in-memory only, dies when this Claude session ends. Use true only when the user asks the task to survive across sessions. */
durable?: boolean
}
CronDelete: {
/** Job ID returned by CronCreate. */
id: string
}
CronList: {}
Edit: {
/** The absolute path to the file to modify */
file_path: string
/** The text to replace */
old_string: string
/** The text to replace it with (must be different from old_string) */
new_string: string
/** Replace all occurrences of old_string (default false) */
replace_all?: boolean
}
EnterWorktree: {
/** Optional name for a new worktree. Each "/"-separated segment may contain only letters, digits, dots, underscores, and dashes; max 64 chars total. A random name is generated if not provided. Mutually exclusive with `path`. */
name?: string
/** Path to an existing worktree to switch into instead of creating a new one. Must appear in `git worktree list` for the current repo β or, on first entry from the launch directory, for a repo nested inside it (multi-repo workspace). Mutually exclusive with `name`. */
path?: string
}
ExitWorktree: {
/** "keep" leaves the worktree and branch on disk; "remove" deletes both. */
action: "keep" | "remove"
/** Required true when action is "remove" and the worktree has uncommitted files or unmerged commits. The tool will refuse and list them otherwise. */
discard_changes?: boolean
}
ListAgents: {
/** Not available in this build; leave unset. */
channel?: string
/** Not available in this build; leave unset. */
q?: string
}
NotebookEdit: {
/** The absolute path to the Jupyter notebook file to edit (must be absolute, not relative) */
notebook_path: string
/** The ID of the cell to edit. When inserting a new cell, the new cell will be inserted after the cell with this ID, or at the beginning if not specified. */
cell_id?: string
/** The new source for the cell */
new_source: string
/** The type of the cell (code or markdown). If not specified, it defaults to the current cell type. If using edit_mode=insert, this is required. */
cell_type?: "code" | "markdown"
/** The type of edit to make (replace, insert, delete). Defaults to replace. */
edit_mode?: "replace" | "insert" | "delete"
}
PowerShell: {
/** The PowerShell command to execute */
command: string
/** Optional timeout in milliseconds (max 600000) */
timeout?: number
/** Clear, concise description of what this command does in active voice. */
description?: string
/** Set to true to run this command in the background. */
run_in_background?: boolean
/** Set this to true to dangerously override sandbox mode and run commands without sandboxing. */
dangerouslyDisableSandbox?: boolean
}
Read: {
/** The absolute path to the file to read */
file_path: string
/** The line number to start reading from. Only provide if the file is too large to read at once */
offset?: number
/** The number of lines to read. Only provide if the file is too large to read at once. */
limit?: number
/** Page range for PDF files (e.g., "1-5", "3", "10-20"). Only applicable to PDF files. Maximum 20 pages per request. */
pages?: string
}
ReportFindings: {
/** Effort level the review ran at */
level?: "low" | "medium" | "high" | "xhigh" | "max"
/** Verified findings, most-severe first; empty if none survived */
findings: Array<{
/** Repo-relative path of the file the finding is in */
file: string
/** 1-indexed line the finding anchors to */
line?: number
/** One-sentence statement of the defect */
summary: string
/** Compressed label for compact UI (β€60 chars): the claim alone, no rationale or consequence clause */
short_summary?: string
/** Concrete inputs/state β wrong output/crash */
failure_scenario: string
/** Short kebab-case slug of the finding type, e.g. "correctness", "simplification", "efficiency", "test-coverage" */
category?: string
/** Set when a verify pass ran; absent on inline-only reviews */
verdict?: "CONFIRMED" | "PLAUSIBLE"
/** Set ONLY when re-reporting after applying fixes: what happened to this finding */
outcome?: "fixed" | "skipped" | "no_change_needed"
}>
}
ScheduleWakeup: {
/** Seconds from now to wake up. Clamped to [60, 3600] by the runtime. Required unless `stop` is true. */
delaySeconds?: number
/** One short sentence explaining the chosen delay. Goes to telemetry and is shown to the user. Be specific. Required unless `stop` is true. */
reason?: string
/** The /loop input to fire on wake-up. Pass the same /loop input verbatim each turn so the next firing re-enters the skill and continues the loop. For autonomous /loop (no user prompt), pass the literal sentinel `<<autonomous-loop-dynamic>>` instead (the dynamic-pacing variant, not the CronCreate-mode `<<autonomous-loop>>`). Required unless `stop` is true. */
prompt?: string
/** Set to true to end the dynamic loop immediately instead of scheduling another wakeup. When true, all other fields are ignored and no further wakeups fire. */
stop?: boolean
/** true = nothing changed (you checked and there is nothing to report). false = something happened worth keeping (edited a file, posted a message, advanced state, surfaced a finding). Consecutive noop:true ticks are collapsed in the user's terminal view and tracked as a streak. Required unless `stop` is true. */
noop?: boolean
}
SendMessage: {
/** Recipient: a name from ListAgents (append its " [ref]" only when a listing or an error shows one), a teammate name, "main", or a background agent's agentId */
to: unknown & unknown
/** A 5-10 word label for your own transcript row (not transmitted β the recipient previews the first line of `message`). Truncated to 200 characters rather than rejected. */
summary?: string
/** Plain text message content. The recipient's human sees only the FIRST LINE as a one-line preview until they expand it, so make the first line a clear, self-contained sentence saying what this is about β not a greeting, preamble, or bare @-mention. */
message: string
/** Ask a session ON THIS MACHINE to send you ONE notice when it next goes idle (finishes its turn with nothing queued) or exits β opt-in, one-shot, no polling. With a message: deliver it now AND subscribe. Without a message (omit it): a pure subscription that costs the other session nothing. */
notify_when_idle?: boolean
}
Skill: {
/** The name of a skill from the available-skills list. Do not guess names. */
skill: string
/** Optional arguments for the skill */
args?: string
}
TaskOutput: {
/** The task ID to get output from */
task_id: string
/** Whether to wait for completion */
block: boolean
/** Max wait time in ms */
timeout: number
}
TaskStop: {
/** The ID of the background task to stop. Agent-team teammates and named background agents are also accepted by agent ID or name. */
task_id?: string
/** Deprecated: use task_id instead */
shell_id?: string
}
ToolSearch: {
/** Query to find deferred tools. Use "select:<tool_name>" for direct selection, or keywords to search. */
query: string
/** Maximum number of results to return (default: 5) */
max_results: number
}
WebFetch: {
/** The URL to fetch content from */
url: string
/** The prompt to run on the fetched content */
prompt: string
}
WebSearch: {
/** The search query to use */
query: string
/** Only include search results from these domains */
allowed_domains?: string[]
/** Never include search results from these domains */
blocked_domains?: string[]
}
Workflow: {
/** Self-contained workflow script. Must begin with `export const meta = { name, description, phases }` (pure literal, no computed values) followed by the script body using agent()/parallel()/pipeline()/phase(). */
script?: string
/** Name of a predefined workflow (built-in or from .claude/workflows/). Resolves to a self-contained script. */
name?: string
/** Ignored β set the workflow description in the script's `meta` block. */
description?: string
/** Ignored β set the workflow title in the script's `meta` block. */
title?: string
/** Optional input value exposed to the script as the global `args`, verbatim. Pass arrays/objects as actual JSON values, NOT as a JSON-encoded string β a stringified list breaks `args.filter`/`args.map` in the script. Use for parameterized named workflows (e.g. a research question). */
args?: unknown
/** Path to a workflow script file on disk. Every Workflow invocation persists its script under the session directory and returns the path in the tool result. To iterate, edit that file with Write/Edit and re-invoke Workflow with the same `scriptPath` instead of re-sending the full script. Takes precedence over `script` and `name`. */
scriptPath?: string
/** Run ID of a prior Workflow invocation to resume from. Completed agent() calls with unchanged (prompt, opts) return their cached results instantly; only edited or new calls re-run. Same-session only. Stop the prior run first (TaskStop) before resuming. */
resumeFromRunId?: string
}
Write: {
/** The absolute path to the file to write (must be absolute, not relative) */
file_path: string
/** The content to write to the file */
content: string
}
}
}
// The structured results of the same tools, from each tool's output
// schema. Merges into ToolCallResult (BuiltinToolResults) so after
// `e.tool === "Bash"` the `result` of `next(e)` is the tool's record.
declare module 'claude-code' {
interface BuiltinToolResults {
Agent: {
agentId: string
/** @internal Count of leading harness-authored content blocks (hand-back provenance bookkeeping; not a stable consumer field) */
harnessNoteCount?: number
/** @internal Count of trailing harness-authored content blocks (hand-back provenance bookkeeping; not a stable consumer field) */
harnessTailCount?: number
/** @internal Fingerprint binding the harness section counts to the exact content they were computed against; a hook rewrite invalidates the counts rather than misplacing rewritten bytes */
harnessSectionHash?: string
agentType?: string
/** @internal How the report reached this result under the subagent hand-back contract: 'send' = the child's classified SubagentHandback delivery, 'flagged' = that delivery under a SECURITY WARNING, 'withheld' = nothing was delivered (not a stable consumer field) */
handback?: "send" | "flagged" | "withheld"
content: Array<{
type: "text"
text: string
citations?: unknown[] | null
}>
resolvedModel?: string
modelsUsed?: string[]
totalToolUseCount: number
totalDurationMs: number
totalTokens: number
usage: {
input_tokens: number
output_tokens: number
cache_creation_input_tokens: number | null
cache_read_input_tokens: number | null
server_tool_use: {
web_search_requests: number
web_fetch_requests: number
} | null
service_tier: string | null
cache_creation: {
ephemeral_1h_input_tokens: number
ephemeral_5m_input_tokens: number
} | null
inference_geo?: string | null
speed?: string | null
iterations?: unknown
output_tokens_details?: {
thinking_tokens?: number | null
} | null
}
toolStats?: {
readCount: number
searchCount: number
bashCount: number
editFileCount: number
linesAdded: number
linesRemoved: number
otherToolCount: number
frameCount?: number
}
status: "completed"
prompt: string
worktreePath?: string
worktreeBranch?: string
} | {
status: "async_launched"
isAsync?: true
/** The ID of the async agent */
agentId: string
/** The description of the task */
description: string
/** Model in use at the backgrounding transition (a pre-background swap is reflected here) */
resolvedModel?: string
/** Ordered distinct models used before backgrounding (length > 1 means a mid-run swap) */
modelsUsed?: string[]
/** The prompt for the agent */
prompt: string
/** Path to the output file for checking agent progress */
outputFile: string
/** Whether the calling agent has Read/Bash tools to check progress */
canReadOutputFile?: boolean
} | {
status: "remote_launched"
/** The ID of the remote agent task */
taskId: string
/** The URL of the cloud session */
sessionUrl: string
/** The description of the task */
description: string
/** The prompt for the agent */
prompt: string
/** Path to the output file for checking agent progress */
outputFile: string
}
Bash: {
/** The standard output of the command */
stdout: string
/** The standard error output of the command */
stderr: string
/** Path to raw output file for large MCP tool outputs */
rawOutputPath?: string
/** Whether the command was interrupted */
interrupted: boolean
/** Flag to indicate if stdout contains image data */
isImage?: boolean
/** ID of the background task if command is running in background */
backgroundTaskId?: string
/** True if the user manually backgrounded the command with Ctrl+B */
backgroundedByUser?: boolean
/** @internal True if a plugin's turn abort moved the running command to the background */
backgroundedByTurnAbort?: boolean
/** @internal True if the command was moved to the background so a message queued for the model could reach it */
backgroundedToDeliverMessage?: boolean
/** Set when the command hit its timeout and was auto-backgrounded; the timeout value in ms */
timedOutAfterMs?: number
/** Model-facing note that the session cwd was not changed by a backgrounded command containing a directory-change builtin (cd/pushd/popd/chdir) */
backgroundCwdHint?: string
/** True when this backgrounded command is owned by a synchronous subagent and is therefore terminated when that agent gives its final response; absent when the command survives (main loop, async subagents) */
backgroundEndsWithFinalResponse?: true
/** Flag to indicate if sandbox mode was overridden */
dangerouslyDisableSandbox?: boolean
/** Semantic interpretation for non-error exit codes with special meaning */
returnCodeInterpretation?: string
/** Whether the command is expected to produce no output on success */
noOutputExpected?: boolean
/** Structured content blocks */
structuredContent?: unknown[]
/** Path to the persisted full output in tool-results dir (set when output is too large for inline) */
persistedOutputPath?: string
/** Total size of the output in bytes (set when output is too large for inline) */
persistedOutputSize?: number
/** Model-facing note listing readFileState entries whose mtime bumped during this command (set when WRITE_COMMAND_MARKERS matches) */
staleReadFileStateHint?: string
/** Model-facing system-reminder appended when a gh command reports a GitHub API rate-limit error */
ghRateLimitHint?: string
/** Structured classification of git/gh operations detected in this command (commit/push/merge/rebase/PR). Client-facing β lets clients render git activity without re-parsing stdout; not surfaced to the model. */
gitOperation?: {
commit?: {
sha: string
kind: "committed" | "amended" | "cherry-picked"
branch?: string
}
push?: {
branch: string
}
branch?: {
ref: string
action: "merged" | "rebased"
}
pr?: {
number: number
url?: string
action: "created" | "edited" | "merged" | "commented" | "closed" | "reopened" | "ready" | "draft" | "auto-merge-enabled" | "auto-merge-disabled"
}
}
/** @internal Per-file diff of the working-tree changes this command made, for rendering and for PostToolUse Bash hooks (changedFiles: absolute paths of every changed file known, shown or not, at most 200; cut when shorter than files.length + moreFiles); not surfaced to the model. */
bashEditDiff?: {
files: {
filePath: string
hunks: {
oldStart: number
oldLines: number
newStart: number
newLines: number
lines: string[]
}[]
created?: true
deleted?: true
}[]
moreFiles: number
changedFiles?: string[]
unavailable?: true
skipped?: true
shared?: true
}
}
CronCreate: {
id: string
humanSchedule: string
recurring: boolean
durable?: boolean
}
CronDelete: {
id: string
}
CronList: {
jobs: {
id: string
cron: string
humanSchedule: string
prompt: string
recurring?: boolean
durable?: boolean
}[]
}
Edit: {
/** The file path that was edited */
filePath: string
/** The original string that was replaced */
oldString: string
/** The new string that replaced it */
newString: string
/** The original file contents before editing */
originalFile: string | null
/** Diff patch showing the changes */
structuredPatch: {
oldStart: number
oldLines: number
newStart: number
newLines: number
lines: string[]
}[]
/** Whether the user modified the proposed changes */
userModified: boolean
/** Whether all occurrences were replaced */
replaceAll: boolean
gitDiff?: {
filename: string
status: "modified" | "added"
additions: number
deletions: number
changes: number
patch: string
/** GitHub owner/repo when available */
repository?: string | null
}
/** True when the edit was held for the machine owner to review instead of written; the file is unchanged */
staged?: boolean
}
EnterWorktree: {
worktreePath: string
worktreeBranch?: string
message: string
}
ExitWorktree: {
action: "keep" | "remove"
originalCwd: string
worktreePath: string
worktreeBranch?: string
tmuxSessionName?: string
discardedFiles?: number
discardedCommits?: number
message: string
}
ListAgents: {
/** Formatted list of reachable agents */
listing: string
}
NotebookEdit: {
/** The new source code that was written to the cell */
new_source: string
/** The previous cell source (replace/delete only). Enables cell-relative diff rendering without re-reading the notebook. */
old_source?: string
/** The ID of the cell that was edited */
cell_id?: string
/** The type of the cell */
cell_type: "code" | "markdown"
/** The programming language of the notebook */
language: string
/** The edit mode that was used */
edit_mode: string
/** Error message if the operation failed */
error?: string
/** The path to the notebook file */
notebook_path: string
/** The original notebook content before modification */
original_file: string
/** The updated notebook content after modification */
updated_file: string
}
PowerShell: {
/** The standard output of the command */
stdout: string
/** The standard error output of the command */
stderr: string
/** Whether the command was interrupted */
interrupted: boolean
/** Semantic interpretation for non-error exit codes with special meaning */
returnCodeInterpretation?: string
/** Flag to indicate if stdout contains image data */
isImage?: boolean
/** Path to persisted full output when too large for inline */
persistedOutputPath?: string
/** Total output size in bytes when persisted */
persistedOutputSize?: number
/** ID of the background task if command is running in background */
backgroundTaskId?: string
/** True if the user manually backgrounded the command with Ctrl+B */
backgroundedByUser?: boolean
/** @internal True if a plugin's turn abort moved the running command to the background */
backgroundedByTurnAbort?: boolean
/** @internal True if the command was moved to the background so a message queued for the model could reach it */
backgroundedToDeliverMessage?: boolean
/** Set when the command hit its timeout and was auto-backgrounded; the timeout value in ms */
timedOutAfterMs?: number
/** True when this backgrounded command is owned by a synchronous subagent and is therefore terminated when that agent gives its final response; absent when the command survives (main loop, async subagents) */
backgroundEndsWithFinalResponse?: true
/** Structured classification of git/gh operations detected in this command (commit/push/merge/rebase/PR). Client-facing β lets clients render git activity without re-parsing stdout; not surfaced to the model. */
gitOperation?: {
commit?: {
sha: string
kind: "committed" | "amended" | "cherry-picked"
branch?: string
}
push?: {
branch: string
}
branch?: {
ref: string
action: "merged" | "rebased"
}
pr?: {
number: number
url?: string
action: "created" | "edited" | "merged" | "commented" | "closed" | "reopened" | "ready" | "draft" | "auto-merge-enabled" | "auto-merge-disabled"
}
}
}
Read: {
type: "text"
file: {
/** The path to the file that was read */
filePath: string
/** The content of the file */
content: string
/** Number of lines in the returned content */
numLines: number
/** The starting line number */
startLine: number
/** Total number of lines in the file */
totalLines: number
/** True when a whole-file read was auto-paginated because it exceeded the token cap (the content is a partial first page). A programmatic signal for internal consumers; survives output reconstruction (unlike the render-time banner). */
truncatedByTokenCap?: boolean
}
/** Set when this Read completed a saved Artifact source file: the Artifact and the version of it that now counts as viewed. */
artifactRead?: {
slug: string
ver: string
}
} | {
type: "image"
file: {
/** Base64-encoded image data */
base64: string
/** The MIME type of the image */
type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"
/** Original file size in bytes */
originalSize: number
/** Image dimension info for coordinate mapping */
dimensions?: {
/** Original image width in pixels */
originalWidth?: number
/** Original image height in pixels */
originalHeight?: number
/** Displayed image width in pixels (after resizing) */
displayWidth?: number
/** Displayed image height in pixels (after resizing) */
displayHeight?: number
}
}
} | {
type: "notebook"
file: {
/** The path to the notebook file */
filePath: string
/** Array of notebook cells */
cells: unknown[]
}
} | {
type: "pdf"
file: {
/** The path to the PDF file */
filePath: string
/** Base64-encoded PDF data */
base64: string
/** Original file size in bytes */
originalSize: number
}
} | {
type: "parts"
file: {
/** The path to the PDF file */
filePath: string
/** Original file size in bytes */
originalSize: number
/** Number of pages extracted */
count: number
/** Directory containing extracted page images */
outputDir: string
}
/** Document page number of the first extracted page (1 when no range was requested); labels the page images in the model-facing tool_result */
firstPage?: number
/** Extracted page images, in page order. Present only transiently in-process: the page image bytes are delivered solely as image blocks in the model-facing tool_result content and are not retained on the tool_use_result, so this key is absent on the emitted/persisted result */
pages?: Array<{
/** Base64-encoded page image; empty when the page could not be processed */
base64: string
/** The MIME type of the image */
mediaType: "image/jpeg" | "image/png" | "image/gif" | "image/webp"
/** Why the page could not be processed as an image; set only when base64 is empty */
error?: string
}>
} | {
type: "file_unchanged"
file: {
/** The path to the file */
filePath: string
}
/** Set when the dedup matched a startup-seeded entry (CLAUDE.md / nested memory) rather than a prior Read tool_result */
source?: "seeded"
}
ReportFindings: {
/** Number of findings reported */
count: number
/** Effort level the review ran at */
level?: "low" | "medium" | "high" | "xhigh" | "max"
/** Echoed for the result body */
findings: Array<{
/** Repo-relative path of the file the finding is in */
file: string
/** 1-indexed line the finding anchors to */
line?: number
/** One-sentence statement of the defect */
summary: string
/** Compressed label for compact UI (β€60 chars): the claim alone, no rationale or consequence clause */
short_summary?: string
/** Concrete inputs/state β wrong output/crash */
failure_scenario: string
/** Short kebab-case slug of the finding type, e.g. "correctness", "simplification", "efficiency", "test-coverage" */
category?: string
/** Set when a verify pass ran; absent on inline-only reviews */
verdict?: "CONFIRMED" | "PLAUSIBLE"
/** Set ONLY when re-reporting after applying fixes: what happened to this finding */
outcome?: "fixed" | "skipped" | "no_change_needed"
}>
}
ScheduleWakeup: {
/** Epoch ms timestamp when the next wakeup will fire */
scheduledFor: number
/** Actual delay used after clamping to runtime bounds */
clampedDelaySeconds: number
/** True if the requested delaySeconds was outside [60, 3600] */
wasClamped: boolean
/** True when the model ended the loop via `stop: true` */
stopped?: boolean
/** How many pending dynamic-loop wakeups stop:true cancelled. 0 means nothing was pending β a recurring /loop cron is not cancelled by stop:true. */
cancelledWakeups?: number
}
SendMessage: unknown
Skill: {
/** Whether the skill is valid */
success: boolean
/** The name of the skill */
commandName: string
/** Tools allowed by this skill */
allowedTools?: string[]
/** Resolved model the skill turn runs on when a frontmatter model override took effect; omitted otherwise */
model?: string
/** Execution status */
status?: "inline"
/** True when the skill instructions were loaded read-only (nothing was executed) */
readOnly?: boolean
} | {
/** Whether the skill completed successfully */
success: boolean
/** The name of the skill */
commandName: string
/** Execution status */
status: "forked"
/** The ID of the sub-agent that executed the skill */
agentId: string
/** The result from the forked skill execution */
result: string
/** True when the sub-agent was launched in the background: `result` describes the launch, and the skill outcome arrives later as a task notification. */
background?: boolean
}
TaskOutput: unknown
TaskStop: {
/** Status message about the operation */
message: string
/** The ID of the task that was stopped */
task_id: string
/** The type of the task that was stopped */
task_type: string
/** The command or description of the stopped task */
command?: string
}
ToolSearch: {
matches: string[]
query: string
total_deferred_tools: number
pending_mcp_servers?: string[]
failed_mcp_servers?: {
name: string
errorCode?: string
error?: string
}[]
}
WebFetch: {
/** Size of the fetched content in bytes */
bytes: number
/** HTTP response code */
code: number
/** HTTP response code text */
codeText: string
/** Processed result from applying the prompt to the content */
result: string
/** Time taken to fetch and process the content */
durationMs: number
/** The URL that was fetched */
url: string
artifactRead?: {
slug: string
ver?: string
seeded?: false
}
}
WebSearch: {
/** The search query that was executed */
query: string
/** Search results and/or text commentary from the model */
results: Array<{
/** ID of the tool use */
tool_use_id: string
/** Array of search hits */
content: Array<{
/** The title of the search result */
title: string
/** The URL of the search result */
url: string
}>
} | string>
/** Time taken to complete the search operation */
durationSeconds: number
/** Number of web searches performed */
searchCount?: number
}
Workflow: {
status: "async_launched" | "remote_launched"
taskId: string
/** TaskType of the registered background task β 'local_workflow' for in-process runs, 'remote_agent' when remote:true dispatches to CCR. Set on all new writes; absent only on transcripts written before this field existed. */
taskType?: "local_workflow" | "remote_agent"
/** meta.name from the workflow script β same value as task_started.workflow_name. Set on all new writes; absent only on transcripts written before this field existed. */
workflowName?: string
/** Local workflow run identifier for resumeFromRunId. Absent for remote_launched (the CCR session URL is the resume handle there) and on transcripts written before this field existed. */
runId?: string
summary?: string
/** Directory where subagent transcripts are written during execution */
transcriptDir?: string
/** Path to the persisted workflow script for this invocation. Editable via Write/Edit; pass back as `scriptPath` to re-run without resending the script. */
scriptPath?: string
/** CCR session URL when status is remote_launched */
sessionUrl?: string
/** Non-blocking heads-up (e.g. local git state diverges from the pushed branch the cloud session will clone) */
warning?: string
/** Set if syntax check failed */
error?: string
}
Write: {
/** Whether a new file was created or an existing file was updated */
type: "create" | "update"
/** The path to the file that was written */
filePath: string
/** The content that was written to the file */
content: string
/** Diff patch showing the changes (empty when nothing changed, the diff timed out, or β with originalFile null on an update β the previous content was too large to diff) */
structuredPatch: {
oldStart: number
oldLines: number
newStart: number
newLines: number
lines: string[]
}[]
/** The original file content before the write (null for new files, or when the previous content was too large to include) */
originalFile: string | null
gitDiff?: {
filename: string
status: "modified" | "added"
additions: number
deletions: number
changes: number
patch: string
/** GitHub owner/repo when available */
repository?: string | null
}
/** True when the user edited the proposed content in the permission dialog before accepting */
userModified?: boolean
/** True when the write was held for the machine owner to review instead of written; the file is unchanged */
staged?: boolean
}
}
}
|