File size: 135,529 Bytes
f606b10 |
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 |
package executor
import (
"bufio"
"bytes"
"context"
"encoding/base64"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/google/uuid"
kiroauth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/kiro"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
kiroclaude "github.com/router-for-me/CLIProxyAPI/v6/internal/translator/kiro/claude"
kirocommon "github.com/router-for-me/CLIProxyAPI/v6/internal/translator/kiro/common"
kiroopenai "github.com/router-for-me/CLIProxyAPI/v6/internal/translator/kiro/openai"
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
cliproxyauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/executor"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/usage"
sdktranslator "github.com/router-for-me/CLIProxyAPI/v6/sdk/translator"
log "github.com/sirupsen/logrus"
)
const (
// Kiro API common constants
kiroContentType = "application/x-amz-json-1.0"
kiroAcceptStream = "*/*"
// Event Stream frame size constants for boundary protection
// AWS Event Stream binary format: prelude (12 bytes) + headers + payload + message_crc (4 bytes)
// Prelude consists of: total_length (4) + headers_length (4) + prelude_crc (4)
minEventStreamFrameSize = 16 // Minimum: 4(total_len) + 4(headers_len) + 4(prelude_crc) + 4(message_crc)
maxEventStreamMsgSize = 10 << 20 // Maximum message length: 10MB
// Event Stream error type constants
ErrStreamFatal = "fatal" // Connection/authentication errors, not recoverable
ErrStreamMalformed = "malformed" // Format errors, data cannot be parsed
// kiroUserAgent matches amq2api format for User-Agent header (Amazon Q CLI style)
kiroUserAgent = "aws-sdk-rust/1.3.9 os/macos lang/rust/1.87.0"
// kiroFullUserAgent is the complete x-amz-user-agent header matching amq2api (Amazon Q CLI style)
kiroFullUserAgent = "aws-sdk-rust/1.3.9 ua/2.1 api/ssooidc/1.88.0 os/macos lang/rust/1.87.0 m/E app/AmazonQ-For-CLI"
// Kiro IDE style headers (from kiro2api - for IDC auth)
kiroIDEUserAgent = "aws-sdk-js/1.0.18 ua/2.1 os/darwin#25.0.0 lang/js md/nodejs#20.16.0 api/codewhispererstreaming#1.0.18 m/E KiroIDE-0.2.13-66c23a8c5d15afabec89ef9954ef52a119f10d369df04d548fc6c1eac694b0d1"
kiroIDEAmzUserAgent = "aws-sdk-js/1.0.18 KiroIDE-0.2.13-66c23a8c5d15afabec89ef9954ef52a119f10d369df04d548fc6c1eac694b0d1"
kiroIDEAgentModeSpec = "spec"
)
// Real-time usage estimation configuration
// These control how often usage updates are sent during streaming
var (
usageUpdateCharThreshold = 5000 // Send usage update every 5000 characters
usageUpdateTimeInterval = 15 * time.Second // Or every 15 seconds, whichever comes first
)
// kiroEndpointConfig bundles endpoint URL with its compatible Origin and AmzTarget values.
// This solves the "triple mismatch" problem where different endpoints require matching
// Origin and X-Amz-Target header values.
//
// Based on reference implementations:
// - amq2api-main: Uses Amazon Q endpoint with CLI origin and AmazonQDeveloperStreamingService target
// - AIClient-2-API: Uses CodeWhisperer endpoint with AI_EDITOR origin and AmazonCodeWhispererStreamingService target
type kiroEndpointConfig struct {
URL string // Endpoint URL
Origin string // Request Origin: "CLI" for Amazon Q quota, "AI_EDITOR" for Kiro IDE quota
AmzTarget string // X-Amz-Target header value
Name string // Endpoint name for logging
}
// kiroEndpointConfigs defines the available Kiro API endpoints with their compatible configurations.
// The order determines fallback priority: primary endpoint first, then fallbacks.
//
// CRITICAL: Each endpoint MUST use its compatible Origin and AmzTarget values:
// - CodeWhisperer endpoint (codewhisperer.us-east-1.amazonaws.com): Uses AI_EDITOR origin and AmazonCodeWhispererStreamingService target
// - Amazon Q endpoint (q.us-east-1.amazonaws.com): Uses CLI origin and AmazonQDeveloperStreamingService target
//
// Mismatched combinations will result in 403 Forbidden errors.
//
// NOTE: CodeWhisperer is set as the default endpoint because:
// 1. Most tokens come from Kiro IDE / VSCode extensions (AWS Builder ID auth)
// 2. These tokens use AI_EDITOR origin which is only compatible with CodeWhisperer endpoint
// 3. Amazon Q endpoint requires CLI origin which is for Amazon Q CLI tokens
// This matches the AIClient-2-API-main project's configuration.
var kiroEndpointConfigs = []kiroEndpointConfig{
{
URL: "https://codewhisperer.us-east-1.amazonaws.com/generateAssistantResponse",
Origin: "AI_EDITOR",
AmzTarget: "AmazonCodeWhispererStreamingService.GenerateAssistantResponse",
Name: "CodeWhisperer",
},
{
URL: "https://q.us-east-1.amazonaws.com/",
Origin: "CLI",
AmzTarget: "AmazonQDeveloperStreamingService.SendMessage",
Name: "AmazonQ",
},
}
// getKiroEndpointConfigs returns the list of Kiro API endpoint configurations to try in order.
// Supports reordering based on "preferred_endpoint" in auth metadata/attributes.
// For IDC auth method, automatically uses CodeWhisperer endpoint with CLI origin.
func getKiroEndpointConfigs(auth *cliproxyauth.Auth) []kiroEndpointConfig {
if auth == nil {
return kiroEndpointConfigs
}
// For IDC auth, use CodeWhisperer endpoint with AI_EDITOR origin (same as Social auth)
// Based on kiro2api analysis: IDC tokens work with CodeWhisperer endpoint using Bearer auth
// The difference is only in how tokens are refreshed (OIDC with clientId/clientSecret for IDC)
// NOT in how API calls are made - both Social and IDC use the same endpoint/origin
if auth.Metadata != nil {
authMethod, _ := auth.Metadata["auth_method"].(string)
if authMethod == "idc" {
log.Debugf("kiro: IDC auth, using CodeWhisperer endpoint")
return kiroEndpointConfigs
}
}
// Check for preference
var preference string
if auth.Metadata != nil {
if p, ok := auth.Metadata["preferred_endpoint"].(string); ok {
preference = p
}
}
// Check attributes as fallback (e.g. from HTTP headers)
if preference == "" && auth.Attributes != nil {
preference = auth.Attributes["preferred_endpoint"]
}
if preference == "" {
return kiroEndpointConfigs
}
preference = strings.ToLower(strings.TrimSpace(preference))
// Create new slice to avoid modifying global state
var sorted []kiroEndpointConfig
var remaining []kiroEndpointConfig
for _, cfg := range kiroEndpointConfigs {
name := strings.ToLower(cfg.Name)
// Check for matches
// CodeWhisperer aliases: codewhisperer, ide
// AmazonQ aliases: amazonq, q, cli
isMatch := false
if (preference == "codewhisperer" || preference == "ide") && name == "codewhisperer" {
isMatch = true
} else if (preference == "amazonq" || preference == "q" || preference == "cli") && name == "amazonq" {
isMatch = true
}
if isMatch {
sorted = append(sorted, cfg)
} else {
remaining = append(remaining, cfg)
}
}
// If preference didn't match anything, return default
if len(sorted) == 0 {
return kiroEndpointConfigs
}
// Combine: preferred first, then others
return append(sorted, remaining...)
}
// KiroExecutor handles requests to AWS CodeWhisperer (Kiro) API.
type KiroExecutor struct {
cfg *config.Config
refreshMu sync.Mutex // Serializes token refresh operations to prevent race conditions
}
// isIDCAuth checks if the auth uses IDC (Identity Center) authentication method.
func isIDCAuth(auth *cliproxyauth.Auth) bool {
if auth == nil || auth.Metadata == nil {
return false
}
authMethod, _ := auth.Metadata["auth_method"].(string)
return authMethod == "idc"
}
// buildKiroPayloadForFormat builds the Kiro API payload based on the source format.
// This is critical because OpenAI and Claude formats have different tool structures:
// - OpenAI: tools[].function.name, tools[].function.description
// - Claude: tools[].name, tools[].description
// headers parameter allows checking Anthropic-Beta header for thinking mode detection.
// Returns the serialized JSON payload and a boolean indicating whether thinking mode was injected.
func buildKiroPayloadForFormat(body []byte, modelID, profileArn, origin string, isAgentic, isChatOnly bool, sourceFormat sdktranslator.Format, headers http.Header) ([]byte, bool) {
switch sourceFormat.String() {
case "openai":
log.Debugf("kiro: using OpenAI payload builder for source format: %s", sourceFormat.String())
return kiroopenai.BuildKiroPayloadFromOpenAI(body, modelID, profileArn, origin, isAgentic, isChatOnly, headers, nil)
default:
// Default to Claude format (also handles "claude", "kiro", etc.)
log.Debugf("kiro: using Claude payload builder for source format: %s", sourceFormat.String())
return kiroclaude.BuildKiroPayload(body, modelID, profileArn, origin, isAgentic, isChatOnly, headers, nil)
}
}
// NewKiroExecutor creates a new Kiro executor instance.
func NewKiroExecutor(cfg *config.Config) *KiroExecutor {
return &KiroExecutor{cfg: cfg}
}
// Identifier returns the unique identifier for this executor.
func (e *KiroExecutor) Identifier() string { return "kiro" }
// PrepareRequest prepares the HTTP request before execution.
func (e *KiroExecutor) PrepareRequest(_ *http.Request, _ *cliproxyauth.Auth) error { return nil }
// Execute sends the request to Kiro API and returns the response.
// Supports automatic token refresh on 401/403 errors.
func (e *KiroExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (resp cliproxyexecutor.Response, err error) {
accessToken, profileArn := kiroCredentials(auth)
if accessToken == "" {
return resp, fmt.Errorf("kiro: access token not found in auth")
}
reporter := newUsageReporter(ctx, e.Identifier(), req.Model, auth)
defer reporter.trackFailure(ctx, &err)
// Check if token is expired before making request
if e.isTokenExpired(accessToken) {
log.Infof("kiro: access token expired, attempting refresh before request")
refreshedAuth, refreshErr := e.Refresh(ctx, auth)
if refreshErr != nil {
log.Warnf("kiro: pre-request token refresh failed: %v", refreshErr)
} else if refreshedAuth != nil {
auth = refreshedAuth
// Persist the refreshed auth to file so subsequent requests use it
if persistErr := e.persistRefreshedAuth(auth); persistErr != nil {
log.Warnf("kiro: failed to persist refreshed auth: %v", persistErr)
}
accessToken, profileArn = kiroCredentials(auth)
log.Infof("kiro: token refreshed successfully before request")
}
}
from := opts.SourceFormat
to := sdktranslator.FromString("kiro")
body := sdktranslator.TranslateRequest(from, to, req.Model, bytes.Clone(req.Payload), true)
kiroModelID := e.mapModelToKiro(req.Model)
// Determine agentic mode and effective profile ARN using helper functions
isAgentic, isChatOnly := determineAgenticMode(req.Model)
effectiveProfileArn := getEffectiveProfileArnWithWarning(auth, profileArn)
// Execute with retry on 401/403 and 429 (quota exhausted)
// Note: currentOrigin and kiroPayload are built inside executeWithRetry for each endpoint
resp, err = e.executeWithRetry(ctx, auth, req, opts, accessToken, effectiveProfileArn, nil, body, from, to, reporter, "", kiroModelID, isAgentic, isChatOnly)
return resp, err
}
// executeWithRetry performs the actual HTTP request with automatic retry on auth errors.
// Supports automatic fallback between endpoints with different quotas:
// - Amazon Q endpoint (CLI origin) uses Amazon Q Developer quota
// - CodeWhisperer endpoint (AI_EDITOR origin) uses Kiro IDE quota
// Also supports multi-endpoint fallback similar to Antigravity implementation.
func (e *KiroExecutor) executeWithRetry(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, accessToken, profileArn string, kiroPayload, body []byte, from, to sdktranslator.Format, reporter *usageReporter, currentOrigin, kiroModelID string, isAgentic, isChatOnly bool) (cliproxyexecutor.Response, error) {
var resp cliproxyexecutor.Response
maxRetries := 2 // Allow retries for token refresh + endpoint fallback
endpointConfigs := getKiroEndpointConfigs(auth)
var last429Err error
for endpointIdx := 0; endpointIdx < len(endpointConfigs); endpointIdx++ {
endpointConfig := endpointConfigs[endpointIdx]
url := endpointConfig.URL
// Use this endpoint's compatible Origin (critical for avoiding 403 errors)
currentOrigin = endpointConfig.Origin
// Rebuild payload with the correct origin for this endpoint
// Each endpoint requires its matching Origin value in the request body
kiroPayload, _ = buildKiroPayloadForFormat(body, kiroModelID, profileArn, currentOrigin, isAgentic, isChatOnly, from, opts.Headers)
log.Debugf("kiro: trying endpoint %d/%d: %s (Name: %s, Origin: %s)",
endpointIdx+1, len(endpointConfigs), url, endpointConfig.Name, currentOrigin)
for attempt := 0; attempt <= maxRetries; attempt++ {
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(kiroPayload))
if err != nil {
return resp, err
}
httpReq.Header.Set("Content-Type", kiroContentType)
httpReq.Header.Set("Accept", kiroAcceptStream)
// Use endpoint-specific X-Amz-Target (critical for avoiding 403 errors)
httpReq.Header.Set("X-Amz-Target", endpointConfig.AmzTarget)
// Use different headers based on auth type
// IDC auth uses Kiro IDE style headers (from kiro2api)
// Other auth types use Amazon Q CLI style headers
if isIDCAuth(auth) {
httpReq.Header.Set("User-Agent", kiroIDEUserAgent)
httpReq.Header.Set("X-Amz-User-Agent", kiroIDEAmzUserAgent)
httpReq.Header.Set("x-amzn-kiro-agent-mode", kiroIDEAgentModeSpec)
log.Debugf("kiro: using Kiro IDE headers for IDC auth")
} else {
httpReq.Header.Set("User-Agent", kiroUserAgent)
httpReq.Header.Set("X-Amz-User-Agent", kiroFullUserAgent)
}
httpReq.Header.Set("Amz-Sdk-Request", "attempt=1; max=3")
httpReq.Header.Set("Amz-Sdk-Invocation-Id", uuid.New().String())
// Bearer token authentication for all auth types (Builder ID, IDC, social, etc.)
httpReq.Header.Set("Authorization", "Bearer "+accessToken)
var attrs map[string]string
if auth != nil {
attrs = auth.Attributes
}
util.ApplyCustomHeadersFromAttrs(httpReq, attrs)
var authID, authLabel, authType, authValue string
if auth != nil {
authID = auth.ID
authLabel = auth.Label
authType, authValue = auth.AccountInfo()
}
recordAPIRequest(ctx, e.cfg, upstreamRequestLog{
URL: url,
Method: http.MethodPost,
Headers: httpReq.Header.Clone(),
Body: kiroPayload,
Provider: e.Identifier(),
AuthID: authID,
AuthLabel: authLabel,
AuthType: authType,
AuthValue: authValue,
})
httpClient := newProxyAwareHTTPClient(ctx, e.cfg, auth, 120*time.Second)
httpResp, err := httpClient.Do(httpReq)
if err != nil {
recordAPIResponseError(ctx, e.cfg, err)
return resp, err
}
recordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone())
// Handle 429 errors (quota exhausted) - try next endpoint
// Each endpoint has its own quota pool, so we can try different endpoints
if httpResp.StatusCode == 429 {
respBody, _ := io.ReadAll(httpResp.Body)
_ = httpResp.Body.Close()
appendAPIResponseChunk(ctx, e.cfg, respBody)
// Preserve last 429 so callers can correctly backoff when all endpoints are exhausted
last429Err = statusErr{code: httpResp.StatusCode, msg: string(respBody)}
log.Warnf("kiro: %s endpoint quota exhausted (429), will try next endpoint, body: %s",
endpointConfig.Name, summarizeErrorBody(httpResp.Header.Get("Content-Type"), respBody))
// Break inner retry loop to try next endpoint (which has different quota)
break
}
// Handle 5xx server errors with exponential backoff retry
if httpResp.StatusCode >= 500 && httpResp.StatusCode < 600 {
respBody, _ := io.ReadAll(httpResp.Body)
_ = httpResp.Body.Close()
appendAPIResponseChunk(ctx, e.cfg, respBody)
if attempt < maxRetries {
// Exponential backoff: 1s, 2s, 4s... (max 30s)
backoff := time.Duration(1<<attempt) * time.Second
if backoff > 30*time.Second {
backoff = 30 * time.Second
}
log.Warnf("kiro: server error %d, retrying in %v (attempt %d/%d)", httpResp.StatusCode, backoff, attempt+1, maxRetries)
time.Sleep(backoff)
continue
}
log.Errorf("kiro: server error %d after %d retries", httpResp.StatusCode, maxRetries)
return resp, statusErr{code: httpResp.StatusCode, msg: string(respBody)}
}
// Handle 401 errors with token refresh and retry
// 401 = Unauthorized (token expired/invalid) - refresh token
if httpResp.StatusCode == 401 {
respBody, _ := io.ReadAll(httpResp.Body)
_ = httpResp.Body.Close()
appendAPIResponseChunk(ctx, e.cfg, respBody)
if attempt < maxRetries {
log.Warnf("kiro: received 401 error, attempting token refresh and retry (attempt %d/%d)", attempt+1, maxRetries+1)
refreshedAuth, refreshErr := e.Refresh(ctx, auth)
if refreshErr != nil {
log.Errorf("kiro: token refresh failed: %v", refreshErr)
return resp, statusErr{code: httpResp.StatusCode, msg: string(respBody)}
}
if refreshedAuth != nil {
auth = refreshedAuth
// Persist the refreshed auth to file so subsequent requests use it
if persistErr := e.persistRefreshedAuth(auth); persistErr != nil {
log.Warnf("kiro: failed to persist refreshed auth: %v", persistErr)
// Continue anyway - the token is valid for this request
}
accessToken, profileArn = kiroCredentials(auth)
// Rebuild payload with new profile ARN if changed
kiroPayload, _ = buildKiroPayloadForFormat(body, kiroModelID, profileArn, currentOrigin, isAgentic, isChatOnly, from, opts.Headers)
log.Infof("kiro: token refreshed successfully, retrying request")
continue
}
}
log.Warnf("kiro request error, status: 401, body: %s", summarizeErrorBody(httpResp.Header.Get("Content-Type"), respBody))
return resp, statusErr{code: httpResp.StatusCode, msg: string(respBody)}
}
// Handle 402 errors - Monthly Limit Reached
if httpResp.StatusCode == 402 {
respBody, _ := io.ReadAll(httpResp.Body)
_ = httpResp.Body.Close()
appendAPIResponseChunk(ctx, e.cfg, respBody)
log.Warnf("kiro: received 402 (monthly limit). Upstream body: %s", string(respBody))
// Return upstream error body directly
return resp, statusErr{code: httpResp.StatusCode, msg: string(respBody)}
}
// Handle 403 errors - Access Denied / Token Expired
// Do NOT switch endpoints for 403 errors
if httpResp.StatusCode == 403 {
respBody, _ := io.ReadAll(httpResp.Body)
_ = httpResp.Body.Close()
appendAPIResponseChunk(ctx, e.cfg, respBody)
// Log the 403 error details for debugging
log.Warnf("kiro: received 403 error (attempt %d/%d), body: %s", attempt+1, maxRetries+1, summarizeErrorBody(httpResp.Header.Get("Content-Type"), respBody))
respBodyStr := string(respBody)
// Check for SUSPENDED status - return immediately without retry
if strings.Contains(respBodyStr, "SUSPENDED") || strings.Contains(respBodyStr, "TEMPORARILY_SUSPENDED") {
log.Errorf("kiro: account is suspended, cannot proceed")
return resp, statusErr{code: httpResp.StatusCode, msg: "account suspended: " + string(respBody)}
}
// Check if this looks like a token-related 403 (some APIs return 403 for expired tokens)
isTokenRelated := strings.Contains(respBodyStr, "token") ||
strings.Contains(respBodyStr, "expired") ||
strings.Contains(respBodyStr, "invalid") ||
strings.Contains(respBodyStr, "unauthorized")
if isTokenRelated && attempt < maxRetries {
log.Warnf("kiro: 403 appears token-related, attempting token refresh")
refreshedAuth, refreshErr := e.Refresh(ctx, auth)
if refreshErr != nil {
log.Errorf("kiro: token refresh failed: %v", refreshErr)
// Token refresh failed - return error immediately
return resp, statusErr{code: httpResp.StatusCode, msg: string(respBody)}
}
if refreshedAuth != nil {
auth = refreshedAuth
// Persist the refreshed auth to file so subsequent requests use it
if persistErr := e.persistRefreshedAuth(auth); persistErr != nil {
log.Warnf("kiro: failed to persist refreshed auth: %v", persistErr)
// Continue anyway - the token is valid for this request
}
accessToken, profileArn = kiroCredentials(auth)
kiroPayload, _ = buildKiroPayloadForFormat(body, kiroModelID, profileArn, currentOrigin, isAgentic, isChatOnly, from, opts.Headers)
log.Infof("kiro: token refreshed for 403, retrying request")
continue
}
}
// For non-token 403 or after max retries, return error immediately
// Do NOT switch endpoints for 403 errors
log.Warnf("kiro: 403 error, returning immediately (no endpoint switch)")
return resp, statusErr{code: httpResp.StatusCode, msg: string(respBody)}
}
if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 {
b, _ := io.ReadAll(httpResp.Body)
appendAPIResponseChunk(ctx, e.cfg, b)
log.Debugf("kiro request error, status: %d, body: %s", httpResp.StatusCode, summarizeErrorBody(httpResp.Header.Get("Content-Type"), b))
err = statusErr{code: httpResp.StatusCode, msg: string(b)}
if errClose := httpResp.Body.Close(); errClose != nil {
log.Errorf("response body close error: %v", errClose)
}
return resp, err
}
defer func() {
if errClose := httpResp.Body.Close(); errClose != nil {
log.Errorf("response body close error: %v", errClose)
}
}()
content, toolUses, usageInfo, stopReason, err := e.parseEventStream(httpResp.Body)
if err != nil {
recordAPIResponseError(ctx, e.cfg, err)
return resp, err
}
// Fallback for usage if missing from upstream
if usageInfo.TotalTokens == 0 {
if enc, encErr := getTokenizer(req.Model); encErr == nil {
if inp, countErr := countOpenAIChatTokens(enc, opts.OriginalRequest); countErr == nil {
usageInfo.InputTokens = inp
}
}
if len(content) > 0 {
// Use tiktoken for more accurate output token calculation
if enc, encErr := getTokenizer(req.Model); encErr == nil {
if tokenCount, countErr := enc.Count(content); countErr == nil {
usageInfo.OutputTokens = int64(tokenCount)
}
}
// Fallback to character count estimation if tiktoken fails
if usageInfo.OutputTokens == 0 {
usageInfo.OutputTokens = int64(len(content) / 4)
if usageInfo.OutputTokens == 0 {
usageInfo.OutputTokens = 1
}
}
}
usageInfo.TotalTokens = usageInfo.InputTokens + usageInfo.OutputTokens
}
appendAPIResponseChunk(ctx, e.cfg, []byte(content))
reporter.publish(ctx, usageInfo)
// Build response in Claude format for Kiro translator
// stopReason is extracted from upstream response by parseEventStream
kiroResponse := kiroclaude.BuildClaudeResponse(content, toolUses, req.Model, usageInfo, stopReason)
out := sdktranslator.TranslateNonStream(ctx, to, from, req.Model, bytes.Clone(opts.OriginalRequest), body, kiroResponse, nil)
resp = cliproxyexecutor.Response{Payload: []byte(out)}
return resp, nil
}
// Inner retry loop exhausted for this endpoint, try next endpoint
// Note: This code is unreachable because all paths in the inner loop
// either return or continue. Kept as comment for documentation.
}
// All endpoints exhausted
if last429Err != nil {
return resp, last429Err
}
return resp, fmt.Errorf("kiro: all endpoints exhausted")
}
// ExecuteStream handles streaming requests to Kiro API.
// Supports automatic token refresh on 401/403 errors and quota fallback on 429.
func (e *KiroExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (stream <-chan cliproxyexecutor.StreamChunk, err error) {
accessToken, profileArn := kiroCredentials(auth)
if accessToken == "" {
return nil, fmt.Errorf("kiro: access token not found in auth")
}
reporter := newUsageReporter(ctx, e.Identifier(), req.Model, auth)
defer reporter.trackFailure(ctx, &err)
// Check if token is expired before making request
if e.isTokenExpired(accessToken) {
log.Infof("kiro: access token expired, attempting refresh before stream request")
refreshedAuth, refreshErr := e.Refresh(ctx, auth)
if refreshErr != nil {
log.Warnf("kiro: pre-request token refresh failed: %v", refreshErr)
} else if refreshedAuth != nil {
auth = refreshedAuth
// Persist the refreshed auth to file so subsequent requests use it
if persistErr := e.persistRefreshedAuth(auth); persistErr != nil {
log.Warnf("kiro: failed to persist refreshed auth: %v", persistErr)
}
accessToken, profileArn = kiroCredentials(auth)
log.Infof("kiro: token refreshed successfully before stream request")
}
}
from := opts.SourceFormat
to := sdktranslator.FromString("kiro")
body := sdktranslator.TranslateRequest(from, to, req.Model, bytes.Clone(req.Payload), true)
kiroModelID := e.mapModelToKiro(req.Model)
// Determine agentic mode and effective profile ARN using helper functions
isAgentic, isChatOnly := determineAgenticMode(req.Model)
effectiveProfileArn := getEffectiveProfileArnWithWarning(auth, profileArn)
// Execute stream with retry on 401/403 and 429 (quota exhausted)
// Note: currentOrigin and kiroPayload are built inside executeStreamWithRetry for each endpoint
return e.executeStreamWithRetry(ctx, auth, req, opts, accessToken, effectiveProfileArn, nil, body, from, reporter, "", kiroModelID, isAgentic, isChatOnly)
}
// executeStreamWithRetry performs the streaming HTTP request with automatic retry on auth errors.
// Supports automatic fallback between endpoints with different quotas:
// - Amazon Q endpoint (CLI origin) uses Amazon Q Developer quota
// - CodeWhisperer endpoint (AI_EDITOR origin) uses Kiro IDE quota
// Also supports multi-endpoint fallback similar to Antigravity implementation.
func (e *KiroExecutor) executeStreamWithRetry(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, accessToken, profileArn string, kiroPayload, body []byte, from sdktranslator.Format, reporter *usageReporter, currentOrigin, kiroModelID string, isAgentic, isChatOnly bool) (<-chan cliproxyexecutor.StreamChunk, error) {
maxRetries := 2 // Allow retries for token refresh + endpoint fallback
endpointConfigs := getKiroEndpointConfigs(auth)
var last429Err error
for endpointIdx := 0; endpointIdx < len(endpointConfigs); endpointIdx++ {
endpointConfig := endpointConfigs[endpointIdx]
url := endpointConfig.URL
// Use this endpoint's compatible Origin (critical for avoiding 403 errors)
currentOrigin = endpointConfig.Origin
// Rebuild payload with the correct origin for this endpoint
// Each endpoint requires its matching Origin value in the request body
kiroPayload, thinkingEnabled := buildKiroPayloadForFormat(body, kiroModelID, profileArn, currentOrigin, isAgentic, isChatOnly, from, opts.Headers)
log.Debugf("kiro: stream trying endpoint %d/%d: %s (Name: %s, Origin: %s)",
endpointIdx+1, len(endpointConfigs), url, endpointConfig.Name, currentOrigin)
for attempt := 0; attempt <= maxRetries; attempt++ {
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(kiroPayload))
if err != nil {
return nil, err
}
httpReq.Header.Set("Content-Type", kiroContentType)
httpReq.Header.Set("Accept", kiroAcceptStream)
// Use endpoint-specific X-Amz-Target (critical for avoiding 403 errors)
httpReq.Header.Set("X-Amz-Target", endpointConfig.AmzTarget)
// Use different headers based on auth type
// IDC auth uses Kiro IDE style headers (from kiro2api)
// Other auth types use Amazon Q CLI style headers
if isIDCAuth(auth) {
httpReq.Header.Set("User-Agent", kiroIDEUserAgent)
httpReq.Header.Set("X-Amz-User-Agent", kiroIDEAmzUserAgent)
httpReq.Header.Set("x-amzn-kiro-agent-mode", kiroIDEAgentModeSpec)
log.Debugf("kiro: using Kiro IDE headers for IDC auth")
} else {
httpReq.Header.Set("User-Agent", kiroUserAgent)
httpReq.Header.Set("X-Amz-User-Agent", kiroFullUserAgent)
}
httpReq.Header.Set("Amz-Sdk-Request", "attempt=1; max=3")
httpReq.Header.Set("Amz-Sdk-Invocation-Id", uuid.New().String())
// Bearer token authentication for all auth types (Builder ID, IDC, social, etc.)
httpReq.Header.Set("Authorization", "Bearer "+accessToken)
var attrs map[string]string
if auth != nil {
attrs = auth.Attributes
}
util.ApplyCustomHeadersFromAttrs(httpReq, attrs)
var authID, authLabel, authType, authValue string
if auth != nil {
authID = auth.ID
authLabel = auth.Label
authType, authValue = auth.AccountInfo()
}
recordAPIRequest(ctx, e.cfg, upstreamRequestLog{
URL: url,
Method: http.MethodPost,
Headers: httpReq.Header.Clone(),
Body: kiroPayload,
Provider: e.Identifier(),
AuthID: authID,
AuthLabel: authLabel,
AuthType: authType,
AuthValue: authValue,
})
httpClient := newProxyAwareHTTPClient(ctx, e.cfg, auth, 0)
httpResp, err := httpClient.Do(httpReq)
if err != nil {
recordAPIResponseError(ctx, e.cfg, err)
return nil, err
}
recordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone())
// Handle 429 errors (quota exhausted) - try next endpoint
// Each endpoint has its own quota pool, so we can try different endpoints
if httpResp.StatusCode == 429 {
respBody, _ := io.ReadAll(httpResp.Body)
_ = httpResp.Body.Close()
appendAPIResponseChunk(ctx, e.cfg, respBody)
// Preserve last 429 so callers can correctly backoff when all endpoints are exhausted
last429Err = statusErr{code: httpResp.StatusCode, msg: string(respBody)}
log.Warnf("kiro: stream %s endpoint quota exhausted (429), will try next endpoint, body: %s",
endpointConfig.Name, summarizeErrorBody(httpResp.Header.Get("Content-Type"), respBody))
// Break inner retry loop to try next endpoint (which has different quota)
break
}
// Handle 5xx server errors with exponential backoff retry
if httpResp.StatusCode >= 500 && httpResp.StatusCode < 600 {
respBody, _ := io.ReadAll(httpResp.Body)
_ = httpResp.Body.Close()
appendAPIResponseChunk(ctx, e.cfg, respBody)
if attempt < maxRetries {
// Exponential backoff: 1s, 2s, 4s... (max 30s)
backoff := time.Duration(1<<attempt) * time.Second
if backoff > 30*time.Second {
backoff = 30 * time.Second
}
log.Warnf("kiro: stream server error %d, retrying in %v (attempt %d/%d)", httpResp.StatusCode, backoff, attempt+1, maxRetries)
time.Sleep(backoff)
continue
}
log.Errorf("kiro: stream server error %d after %d retries", httpResp.StatusCode, maxRetries)
return nil, statusErr{code: httpResp.StatusCode, msg: string(respBody)}
}
// Handle 400 errors - Credential/Validation issues
// Do NOT switch endpoints - return error immediately
if httpResp.StatusCode == 400 {
respBody, _ := io.ReadAll(httpResp.Body)
_ = httpResp.Body.Close()
appendAPIResponseChunk(ctx, e.cfg, respBody)
log.Warnf("kiro: received 400 error (attempt %d/%d), body: %s", attempt+1, maxRetries+1, summarizeErrorBody(httpResp.Header.Get("Content-Type"), respBody))
// 400 errors indicate request validation issues - return immediately without retry
return nil, statusErr{code: httpResp.StatusCode, msg: string(respBody)}
}
// Handle 401 errors with token refresh and retry
// 401 = Unauthorized (token expired/invalid) - refresh token
if httpResp.StatusCode == 401 {
respBody, _ := io.ReadAll(httpResp.Body)
_ = httpResp.Body.Close()
appendAPIResponseChunk(ctx, e.cfg, respBody)
if attempt < maxRetries {
log.Warnf("kiro: stream received 401 error, attempting token refresh and retry (attempt %d/%d)", attempt+1, maxRetries+1)
refreshedAuth, refreshErr := e.Refresh(ctx, auth)
if refreshErr != nil {
log.Errorf("kiro: token refresh failed: %v", refreshErr)
return nil, statusErr{code: httpResp.StatusCode, msg: string(respBody)}
}
if refreshedAuth != nil {
auth = refreshedAuth
// Persist the refreshed auth to file so subsequent requests use it
if persistErr := e.persistRefreshedAuth(auth); persistErr != nil {
log.Warnf("kiro: failed to persist refreshed auth: %v", persistErr)
// Continue anyway - the token is valid for this request
}
accessToken, profileArn = kiroCredentials(auth)
// Rebuild payload with new profile ARN if changed
kiroPayload, _ = buildKiroPayloadForFormat(body, kiroModelID, profileArn, currentOrigin, isAgentic, isChatOnly, from, opts.Headers)
log.Infof("kiro: token refreshed successfully, retrying stream request")
continue
}
}
log.Warnf("kiro stream error, status: 401, body: %s", string(respBody))
return nil, statusErr{code: httpResp.StatusCode, msg: string(respBody)}
}
// Handle 402 errors - Monthly Limit Reached
if httpResp.StatusCode == 402 {
respBody, _ := io.ReadAll(httpResp.Body)
_ = httpResp.Body.Close()
appendAPIResponseChunk(ctx, e.cfg, respBody)
log.Warnf("kiro: stream received 402 (monthly limit). Upstream body: %s", string(respBody))
// Return upstream error body directly
return nil, statusErr{code: httpResp.StatusCode, msg: string(respBody)}
}
// Handle 403 errors - Access Denied / Token Expired
// Do NOT switch endpoints for 403 errors
if httpResp.StatusCode == 403 {
respBody, _ := io.ReadAll(httpResp.Body)
_ = httpResp.Body.Close()
appendAPIResponseChunk(ctx, e.cfg, respBody)
// Log the 403 error details for debugging
log.Warnf("kiro: stream received 403 error (attempt %d/%d), body: %s", attempt+1, maxRetries+1, string(respBody))
respBodyStr := string(respBody)
// Check for SUSPENDED status - return immediately without retry
if strings.Contains(respBodyStr, "SUSPENDED") || strings.Contains(respBodyStr, "TEMPORARILY_SUSPENDED") {
log.Errorf("kiro: account is suspended, cannot proceed")
return nil, statusErr{code: httpResp.StatusCode, msg: "account suspended: " + string(respBody)}
}
// Check if this looks like a token-related 403 (some APIs return 403 for expired tokens)
isTokenRelated := strings.Contains(respBodyStr, "token") ||
strings.Contains(respBodyStr, "expired") ||
strings.Contains(respBodyStr, "invalid") ||
strings.Contains(respBodyStr, "unauthorized")
if isTokenRelated && attempt < maxRetries {
log.Warnf("kiro: 403 appears token-related, attempting token refresh")
refreshedAuth, refreshErr := e.Refresh(ctx, auth)
if refreshErr != nil {
log.Errorf("kiro: token refresh failed: %v", refreshErr)
// Token refresh failed - return error immediately
return nil, statusErr{code: httpResp.StatusCode, msg: string(respBody)}
}
if refreshedAuth != nil {
auth = refreshedAuth
// Persist the refreshed auth to file so subsequent requests use it
if persistErr := e.persistRefreshedAuth(auth); persistErr != nil {
log.Warnf("kiro: failed to persist refreshed auth: %v", persistErr)
// Continue anyway - the token is valid for this request
}
accessToken, profileArn = kiroCredentials(auth)
kiroPayload, _ = buildKiroPayloadForFormat(body, kiroModelID, profileArn, currentOrigin, isAgentic, isChatOnly, from, opts.Headers)
log.Infof("kiro: token refreshed for 403, retrying stream request")
continue
}
}
// For non-token 403 or after max retries, return error immediately
// Do NOT switch endpoints for 403 errors
log.Warnf("kiro: 403 error, returning immediately (no endpoint switch)")
return nil, statusErr{code: httpResp.StatusCode, msg: string(respBody)}
}
if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 {
b, _ := io.ReadAll(httpResp.Body)
appendAPIResponseChunk(ctx, e.cfg, b)
log.Debugf("kiro stream error, status: %d, body: %s", httpResp.StatusCode, string(b))
if errClose := httpResp.Body.Close(); errClose != nil {
log.Errorf("response body close error: %v", errClose)
}
return nil, statusErr{code: httpResp.StatusCode, msg: string(b)}
}
out := make(chan cliproxyexecutor.StreamChunk)
go func(resp *http.Response, thinkingEnabled bool) {
defer close(out)
defer func() {
if r := recover(); r != nil {
log.Errorf("kiro: panic in stream handler: %v", r)
out <- cliproxyexecutor.StreamChunk{Err: fmt.Errorf("internal error: %v", r)}
}
}()
defer func() {
if errClose := resp.Body.Close(); errClose != nil {
log.Errorf("response body close error: %v", errClose)
}
}()
// Kiro API always returns <thinking> tags regardless of request parameters
// So we always enable thinking parsing for Kiro responses
log.Debugf("kiro: stream thinkingEnabled = %v (always true for Kiro)", thinkingEnabled)
e.streamToChannel(ctx, resp.Body, out, from, req.Model, opts.OriginalRequest, body, reporter, thinkingEnabled)
}(httpResp, thinkingEnabled)
return out, nil
}
// Inner retry loop exhausted for this endpoint, try next endpoint
// Note: This code is unreachable because all paths in the inner loop
// either return or continue. Kept as comment for documentation.
}
// All endpoints exhausted
if last429Err != nil {
return nil, last429Err
}
return nil, fmt.Errorf("kiro: stream all endpoints exhausted")
}
// kiroCredentials extracts access token and profile ARN from auth.
func kiroCredentials(auth *cliproxyauth.Auth) (accessToken, profileArn string) {
if auth == nil {
return "", ""
}
// Try Metadata first (wrapper format)
if auth.Metadata != nil {
if token, ok := auth.Metadata["access_token"].(string); ok {
accessToken = token
}
if arn, ok := auth.Metadata["profile_arn"].(string); ok {
profileArn = arn
}
}
// Try Attributes
if accessToken == "" && auth.Attributes != nil {
accessToken = auth.Attributes["access_token"]
profileArn = auth.Attributes["profile_arn"]
}
// Try direct fields from flat JSON format (new AWS Builder ID format)
if accessToken == "" && auth.Metadata != nil {
if token, ok := auth.Metadata["accessToken"].(string); ok {
accessToken = token
}
if arn, ok := auth.Metadata["profileArn"].(string); ok {
profileArn = arn
}
}
return accessToken, profileArn
}
// findRealThinkingEndTag finds the real </thinking> end tag, skipping false positives.
// Returns -1 if no real end tag is found.
//
// Real </thinking> tags from Kiro API have specific characteristics:
// - Usually preceded by newline (.\n</thinking>)
// - Usually followed by newline (\n\n)
// - Not inside code blocks or inline code
//
// False positives (discussion text) have characteristics:
// - In the middle of a sentence
// - Preceded by discussion words like "标签", "tag", "returns"
// - Inside code blocks or inline code
//
// Parameters:
// - content: the content to search in
// - alreadyInCodeBlock: whether we're already inside a code block from previous chunks
// - alreadyInInlineCode: whether we're already inside inline code from previous chunks
func findRealThinkingEndTag(content string, alreadyInCodeBlock, alreadyInInlineCode bool) int {
searchStart := 0
for {
endIdx := strings.Index(content[searchStart:], kirocommon.ThinkingEndTag)
if endIdx < 0 {
return -1
}
endIdx += searchStart // Adjust to absolute position
textBeforeEnd := content[:endIdx]
textAfterEnd := content[endIdx+len(kirocommon.ThinkingEndTag):]
// Check 1: Is it inside inline code?
// Count backticks in current content and add state from previous chunks
backtickCount := strings.Count(textBeforeEnd, "`")
effectiveInInlineCode := alreadyInInlineCode
if backtickCount%2 == 1 {
effectiveInInlineCode = !effectiveInInlineCode
}
if effectiveInInlineCode {
log.Debugf("kiro: found </thinking> inside inline code at pos %d, skipping", endIdx)
searchStart = endIdx + len(kirocommon.ThinkingEndTag)
continue
}
// Check 2: Is it inside a code block?
// Count fences in current content and add state from previous chunks
fenceCount := strings.Count(textBeforeEnd, "```")
altFenceCount := strings.Count(textBeforeEnd, "~~~")
effectiveInCodeBlock := alreadyInCodeBlock
if fenceCount%2 == 1 || altFenceCount%2 == 1 {
effectiveInCodeBlock = !effectiveInCodeBlock
}
if effectiveInCodeBlock {
log.Debugf("kiro: found </thinking> inside code block at pos %d, skipping", endIdx)
searchStart = endIdx + len(kirocommon.ThinkingEndTag)
continue
}
// Check 3: Real </thinking> tags are usually preceded by newline or at start
// and followed by newline or at end. Check the format.
charBeforeTag := byte(0)
if endIdx > 0 {
charBeforeTag = content[endIdx-1]
}
charAfterTag := byte(0)
if len(textAfterEnd) > 0 {
charAfterTag = textAfterEnd[0]
}
// Real end tag format: preceded by newline OR end of sentence (. ! ?)
// and followed by newline OR end of content
isPrecededByNewlineOrSentenceEnd := charBeforeTag == '\n' || charBeforeTag == '.' ||
charBeforeTag == '!' || charBeforeTag == '?' || charBeforeTag == 0
isFollowedByNewlineOrEnd := charAfterTag == '\n' || charAfterTag == 0
// If the tag has proper formatting (newline before/after), it's likely real
if isPrecededByNewlineOrSentenceEnd && isFollowedByNewlineOrEnd {
log.Debugf("kiro: found properly formatted </thinking> at pos %d", endIdx)
return endIdx
}
// Check 4: Is the tag preceded by discussion keywords on the same line?
lastNewlineIdx := strings.LastIndex(textBeforeEnd, "\n")
lineBeforeTag := textBeforeEnd
if lastNewlineIdx >= 0 {
lineBeforeTag = textBeforeEnd[lastNewlineIdx+1:]
}
lineBeforeTagLower := strings.ToLower(lineBeforeTag)
// Discussion patterns - if found, this is likely discussion text
discussionPatterns := []string{
"标签", "返回", "输出", "包含", "使用", "解析", "转换", "生成", // Chinese
"tag", "return", "output", "contain", "use", "parse", "emit", "convert", "generate", // English
"<thinking>", // discussing both tags together
"`</thinking>`", // explicitly in inline code
}
isDiscussion := false
for _, pattern := range discussionPatterns {
if strings.Contains(lineBeforeTagLower, pattern) {
isDiscussion = true
break
}
}
if isDiscussion {
log.Debugf("kiro: found </thinking> after discussion text at pos %d, skipping", endIdx)
searchStart = endIdx + len(kirocommon.ThinkingEndTag)
continue
}
// Check 5: Is there text immediately after on the same line?
// Real end tags don't have text immediately after on the same line
if len(textAfterEnd) > 0 && charAfterTag != '\n' && charAfterTag != 0 {
// Find the next newline
nextNewline := strings.Index(textAfterEnd, "\n")
var textOnSameLine string
if nextNewline >= 0 {
textOnSameLine = textAfterEnd[:nextNewline]
} else {
textOnSameLine = textAfterEnd
}
// If there's non-whitespace text on the same line after the tag, it's discussion
if strings.TrimSpace(textOnSameLine) != "" {
log.Debugf("kiro: found </thinking> with text after on same line at pos %d, skipping", endIdx)
searchStart = endIdx + len(kirocommon.ThinkingEndTag)
continue
}
}
// Check 6: Is there another <thinking> tag after this </thinking>?
if strings.Contains(textAfterEnd, kirocommon.ThinkingStartTag) {
nextStartIdx := strings.Index(textAfterEnd, kirocommon.ThinkingStartTag)
textBeforeNextStart := textAfterEnd[:nextStartIdx]
nextBacktickCount := strings.Count(textBeforeNextStart, "`")
nextFenceCount := strings.Count(textBeforeNextStart, "```")
nextAltFenceCount := strings.Count(textBeforeNextStart, "~~~")
// If the next <thinking> is NOT in code, then this </thinking> is discussion text
if nextBacktickCount%2 == 0 && nextFenceCount%2 == 0 && nextAltFenceCount%2 == 0 {
log.Debugf("kiro: found </thinking> followed by <thinking> at pos %d, likely discussion text, skipping", endIdx)
searchStart = endIdx + len(kirocommon.ThinkingEndTag)
continue
}
}
// This looks like a real end tag
return endIdx
}
}
// determineAgenticMode determines if the model is an agentic or chat-only variant.
// Returns (isAgentic, isChatOnly) based on model name suffixes.
func determineAgenticMode(model string) (isAgentic, isChatOnly bool) {
isAgentic = strings.HasSuffix(model, "-agentic")
isChatOnly = strings.HasSuffix(model, "-chat")
return isAgentic, isChatOnly
}
// getEffectiveProfileArn determines if profileArn should be included based on auth method.
// profileArn is only needed for social auth (Google OAuth), not for builder-id (AWS SSO).
func getEffectiveProfileArn(auth *cliproxyauth.Auth, profileArn string) string {
if auth != nil && auth.Metadata != nil {
if authMethod, ok := auth.Metadata["auth_method"].(string); ok && authMethod == "builder-id" {
return "" // Don't include profileArn for builder-id auth
}
}
return profileArn
}
// getEffectiveProfileArnWithWarning determines if profileArn should be included based on auth method,
// and logs a warning if profileArn is missing for non-builder-id auth.
// This consolidates the auth_method check that was previously done separately.
func getEffectiveProfileArnWithWarning(auth *cliproxyauth.Auth, profileArn string) string {
if auth != nil && auth.Metadata != nil {
if authMethod, ok := auth.Metadata["auth_method"].(string); ok && (authMethod == "builder-id" || authMethod == "idc") {
// builder-id and idc auth don't need profileArn
return ""
}
}
// For non-builder-id/idc auth (social auth), profileArn is required
if profileArn == "" {
log.Warnf("kiro: profile ARN not found in auth, API calls may fail")
}
return profileArn
}
// mapModelToKiro maps external model names to Kiro model IDs.
// Supports both Kiro and Amazon Q prefixes since they use the same API.
// Agentic variants (-agentic suffix) map to the same backend model IDs.
func (e *KiroExecutor) mapModelToKiro(model string) string {
modelMap := map[string]string{
// Amazon Q format (amazonq- prefix) - same API as Kiro
"amazonq-auto": "auto",
"amazonq-claude-opus-4-5": "claude-opus-4.5",
"amazonq-claude-sonnet-4-5": "claude-sonnet-4.5",
"amazonq-claude-sonnet-4-5-20250929": "claude-sonnet-4.5",
"amazonq-claude-sonnet-4": "claude-sonnet-4",
"amazonq-claude-sonnet-4-20250514": "claude-sonnet-4",
"amazonq-claude-haiku-4-5": "claude-haiku-4.5",
// Kiro format (kiro- prefix) - valid model names that should be preserved
"kiro-claude-opus-4-5": "claude-opus-4.5",
"kiro-claude-sonnet-4-5": "claude-sonnet-4.5",
"kiro-claude-sonnet-4-5-20250929": "claude-sonnet-4.5",
"kiro-claude-sonnet-4": "claude-sonnet-4",
"kiro-claude-sonnet-4-20250514": "claude-sonnet-4",
"kiro-claude-haiku-4-5": "claude-haiku-4.5",
"kiro-auto": "auto",
// Native format (no prefix) - used by Kiro IDE directly
"claude-opus-4-5": "claude-opus-4.5",
"claude-opus-4.5": "claude-opus-4.5",
"claude-haiku-4-5": "claude-haiku-4.5",
"claude-haiku-4.5": "claude-haiku-4.5",
"claude-sonnet-4-5": "claude-sonnet-4.5",
"claude-sonnet-4-5-20250929": "claude-sonnet-4.5",
"claude-sonnet-4.5": "claude-sonnet-4.5",
"claude-sonnet-4": "claude-sonnet-4",
"claude-sonnet-4-20250514": "claude-sonnet-4",
"auto": "auto",
// Agentic variants (same backend model IDs, but with special system prompt)
"claude-opus-4.5-agentic": "claude-opus-4.5",
"claude-sonnet-4.5-agentic": "claude-sonnet-4.5",
"claude-sonnet-4-agentic": "claude-sonnet-4",
"claude-haiku-4.5-agentic": "claude-haiku-4.5",
"kiro-claude-opus-4-5-agentic": "claude-opus-4.5",
"kiro-claude-sonnet-4-5-agentic": "claude-sonnet-4.5",
"kiro-claude-sonnet-4-agentic": "claude-sonnet-4",
"kiro-claude-haiku-4-5-agentic": "claude-haiku-4.5",
}
if kiroID, ok := modelMap[model]; ok {
return kiroID
}
// Smart fallback: try to infer model type from name patterns
modelLower := strings.ToLower(model)
// Check for Haiku variants
if strings.Contains(modelLower, "haiku") {
log.Debugf("kiro: unknown Haiku model '%s', mapping to claude-haiku-4.5", model)
return "claude-haiku-4.5"
}
// Check for Sonnet variants
if strings.Contains(modelLower, "sonnet") {
// Check for specific version patterns
if strings.Contains(modelLower, "3-7") || strings.Contains(modelLower, "3.7") {
log.Debugf("kiro: unknown Sonnet 3.7 model '%s', mapping to claude-3-7-sonnet-20250219", model)
return "claude-3-7-sonnet-20250219"
}
if strings.Contains(modelLower, "4-5") || strings.Contains(modelLower, "4.5") {
log.Debugf("kiro: unknown Sonnet 4.5 model '%s', mapping to claude-sonnet-4.5", model)
return "claude-sonnet-4.5"
}
// Default to Sonnet 4
log.Debugf("kiro: unknown Sonnet model '%s', mapping to claude-sonnet-4", model)
return "claude-sonnet-4"
}
// Check for Opus variants
if strings.Contains(modelLower, "opus") {
log.Debugf("kiro: unknown Opus model '%s', mapping to claude-opus-4.5", model)
return "claude-opus-4.5"
}
// Final fallback to Sonnet 4.5 (most commonly used model)
log.Warnf("kiro: unknown model '%s', falling back to claude-sonnet-4.5", model)
return "claude-sonnet-4.5"
}
// EventStreamError represents an Event Stream processing error
type EventStreamError struct {
Type string // "fatal", "malformed"
Message string
Cause error
}
func (e *EventStreamError) Error() string {
if e.Cause != nil {
return fmt.Sprintf("event stream %s: %s: %v", e.Type, e.Message, e.Cause)
}
return fmt.Sprintf("event stream %s: %s", e.Type, e.Message)
}
// eventStreamMessage represents a parsed AWS Event Stream message
type eventStreamMessage struct {
EventType string // Event type from headers (e.g., "assistantResponseEvent")
Payload []byte // JSON payload of the message
}
// NOTE: Request building functions moved to internal/translator/kiro/claude/kiro_claude_request.go
// The executor now uses kiroclaude.BuildKiroPayload() instead
// parseEventStream parses AWS Event Stream binary format.
// Extracts text content, tool uses, and stop_reason from the response.
// Supports embedded [Called ...] tool calls and input buffering for toolUseEvent.
// Returns: content, toolUses, usageInfo, stopReason, error
func (e *KiroExecutor) parseEventStream(body io.Reader) (string, []kiroclaude.KiroToolUse, usage.Detail, string, error) {
var content strings.Builder
var toolUses []kiroclaude.KiroToolUse
var usageInfo usage.Detail
var stopReason string // Extracted from upstream response
reader := bufio.NewReader(body)
// Tool use state tracking for input buffering and deduplication
processedIDs := make(map[string]bool)
var currentToolUse *kiroclaude.ToolUseState
// Upstream usage tracking - Kiro API returns credit usage and context percentage
var upstreamContextPercentage float64 // Context usage percentage from upstream (e.g., 78.56)
for {
msg, eventErr := e.readEventStreamMessage(reader)
if eventErr != nil {
log.Errorf("kiro: parseEventStream error: %v", eventErr)
return content.String(), toolUses, usageInfo, stopReason, eventErr
}
if msg == nil {
// Normal end of stream (EOF)
break
}
eventType := msg.EventType
payload := msg.Payload
if len(payload) == 0 {
continue
}
var event map[string]interface{}
if err := json.Unmarshal(payload, &event); err != nil {
log.Debugf("kiro: skipping malformed event: %v", err)
continue
}
// Check for error/exception events in the payload (Kiro API may return errors with HTTP 200)
// These can appear as top-level fields or nested within the event
if errType, hasErrType := event["_type"].(string); hasErrType {
// AWS-style error: {"_type": "com.amazon.aws.codewhisperer#ValidationException", "message": "..."}
errMsg := ""
if msg, ok := event["message"].(string); ok {
errMsg = msg
}
log.Errorf("kiro: received AWS error in event stream: type=%s, message=%s", errType, errMsg)
return "", nil, usageInfo, stopReason, fmt.Errorf("kiro API error: %s - %s", errType, errMsg)
}
if errType, hasErrType := event["type"].(string); hasErrType && (errType == "error" || errType == "exception") {
// Generic error event
errMsg := ""
if msg, ok := event["message"].(string); ok {
errMsg = msg
} else if errObj, ok := event["error"].(map[string]interface{}); ok {
if msg, ok := errObj["message"].(string); ok {
errMsg = msg
}
}
log.Errorf("kiro: received error event in stream: type=%s, message=%s", errType, errMsg)
return "", nil, usageInfo, stopReason, fmt.Errorf("kiro API error: %s", errMsg)
}
// Extract stop_reason from various event formats
// Kiro/Amazon Q API may include stop_reason in different locations
if sr := kirocommon.GetString(event, "stop_reason"); sr != "" {
stopReason = sr
log.Debugf("kiro: parseEventStream found stop_reason (top-level): %s", stopReason)
}
if sr := kirocommon.GetString(event, "stopReason"); sr != "" {
stopReason = sr
log.Debugf("kiro: parseEventStream found stopReason (top-level): %s", stopReason)
}
// Handle different event types
switch eventType {
case "followupPromptEvent":
// Filter out followupPrompt events - these are UI suggestions, not content
log.Debugf("kiro: parseEventStream ignoring followupPrompt event")
continue
case "assistantResponseEvent":
if assistantResp, ok := event["assistantResponseEvent"].(map[string]interface{}); ok {
if contentText, ok := assistantResp["content"].(string); ok {
content.WriteString(contentText)
}
// Extract stop_reason from assistantResponseEvent
if sr := kirocommon.GetString(assistantResp, "stop_reason"); sr != "" {
stopReason = sr
log.Debugf("kiro: parseEventStream found stop_reason in assistantResponseEvent: %s", stopReason)
}
if sr := kirocommon.GetString(assistantResp, "stopReason"); sr != "" {
stopReason = sr
log.Debugf("kiro: parseEventStream found stopReason in assistantResponseEvent: %s", stopReason)
}
// Extract tool uses from response
if toolUsesRaw, ok := assistantResp["toolUses"].([]interface{}); ok {
for _, tuRaw := range toolUsesRaw {
if tu, ok := tuRaw.(map[string]interface{}); ok {
toolUseID := kirocommon.GetStringValue(tu, "toolUseId")
// Check for duplicate
if processedIDs[toolUseID] {
log.Debugf("kiro: skipping duplicate tool use from assistantResponse: %s", toolUseID)
continue
}
processedIDs[toolUseID] = true
toolUse := kiroclaude.KiroToolUse{
ToolUseID: toolUseID,
Name: kirocommon.GetStringValue(tu, "name"),
}
if input, ok := tu["input"].(map[string]interface{}); ok {
toolUse.Input = input
}
toolUses = append(toolUses, toolUse)
}
}
}
}
// Also try direct format
if contentText, ok := event["content"].(string); ok {
content.WriteString(contentText)
}
// Direct tool uses
if toolUsesRaw, ok := event["toolUses"].([]interface{}); ok {
for _, tuRaw := range toolUsesRaw {
if tu, ok := tuRaw.(map[string]interface{}); ok {
toolUseID := kirocommon.GetStringValue(tu, "toolUseId")
// Check for duplicate
if processedIDs[toolUseID] {
log.Debugf("kiro: skipping duplicate direct tool use: %s", toolUseID)
continue
}
processedIDs[toolUseID] = true
toolUse := kiroclaude.KiroToolUse{
ToolUseID: toolUseID,
Name: kirocommon.GetStringValue(tu, "name"),
}
if input, ok := tu["input"].(map[string]interface{}); ok {
toolUse.Input = input
}
toolUses = append(toolUses, toolUse)
}
}
}
case "toolUseEvent":
// Handle dedicated tool use events with input buffering
completedToolUses, newState := kiroclaude.ProcessToolUseEvent(event, currentToolUse, processedIDs)
currentToolUse = newState
toolUses = append(toolUses, completedToolUses...)
case "supplementaryWebLinksEvent":
if inputTokens, ok := event["inputTokens"].(float64); ok {
usageInfo.InputTokens = int64(inputTokens)
}
if outputTokens, ok := event["outputTokens"].(float64); ok {
usageInfo.OutputTokens = int64(outputTokens)
}
case "messageStopEvent", "message_stop":
// Handle message stop events which may contain stop_reason
if sr := kirocommon.GetString(event, "stop_reason"); sr != "" {
stopReason = sr
log.Debugf("kiro: parseEventStream found stop_reason in messageStopEvent: %s", stopReason)
}
if sr := kirocommon.GetString(event, "stopReason"); sr != "" {
stopReason = sr
log.Debugf("kiro: parseEventStream found stopReason in messageStopEvent: %s", stopReason)
}
case "messageMetadataEvent", "metadataEvent":
// Handle message metadata events which contain token counts
// Official format: { tokenUsage: { outputTokens, totalTokens, uncachedInputTokens, cacheReadInputTokens, cacheWriteInputTokens, contextUsagePercentage } }
var metadata map[string]interface{}
if m, ok := event["messageMetadataEvent"].(map[string]interface{}); ok {
metadata = m
} else if m, ok := event["metadataEvent"].(map[string]interface{}); ok {
metadata = m
} else {
metadata = event // event itself might be the metadata
}
// Check for nested tokenUsage object (official format)
if tokenUsage, ok := metadata["tokenUsage"].(map[string]interface{}); ok {
// outputTokens - precise output token count
if outputTokens, ok := tokenUsage["outputTokens"].(float64); ok {
usageInfo.OutputTokens = int64(outputTokens)
log.Infof("kiro: parseEventStream found precise outputTokens in tokenUsage: %d", usageInfo.OutputTokens)
}
// totalTokens - precise total token count
if totalTokens, ok := tokenUsage["totalTokens"].(float64); ok {
usageInfo.TotalTokens = int64(totalTokens)
log.Infof("kiro: parseEventStream found precise totalTokens in tokenUsage: %d", usageInfo.TotalTokens)
}
// uncachedInputTokens - input tokens not from cache
if uncachedInputTokens, ok := tokenUsage["uncachedInputTokens"].(float64); ok {
usageInfo.InputTokens = int64(uncachedInputTokens)
log.Infof("kiro: parseEventStream found uncachedInputTokens in tokenUsage: %d", usageInfo.InputTokens)
}
// cacheReadInputTokens - tokens read from cache
if cacheReadTokens, ok := tokenUsage["cacheReadInputTokens"].(float64); ok {
// Add to input tokens if we have uncached tokens, otherwise use as input
if usageInfo.InputTokens > 0 {
usageInfo.InputTokens += int64(cacheReadTokens)
} else {
usageInfo.InputTokens = int64(cacheReadTokens)
}
log.Debugf("kiro: parseEventStream found cacheReadInputTokens in tokenUsage: %d", int64(cacheReadTokens))
}
// contextUsagePercentage - can be used as fallback for input token estimation
if ctxPct, ok := tokenUsage["contextUsagePercentage"].(float64); ok {
upstreamContextPercentage = ctxPct
log.Debugf("kiro: parseEventStream found contextUsagePercentage in tokenUsage: %.2f%%", ctxPct)
}
}
// Fallback: check for direct fields in metadata (legacy format)
if usageInfo.InputTokens == 0 {
if inputTokens, ok := metadata["inputTokens"].(float64); ok {
usageInfo.InputTokens = int64(inputTokens)
log.Debugf("kiro: parseEventStream found inputTokens in messageMetadataEvent: %d", usageInfo.InputTokens)
}
}
if usageInfo.OutputTokens == 0 {
if outputTokens, ok := metadata["outputTokens"].(float64); ok {
usageInfo.OutputTokens = int64(outputTokens)
log.Debugf("kiro: parseEventStream found outputTokens in messageMetadataEvent: %d", usageInfo.OutputTokens)
}
}
if usageInfo.TotalTokens == 0 {
if totalTokens, ok := metadata["totalTokens"].(float64); ok {
usageInfo.TotalTokens = int64(totalTokens)
log.Debugf("kiro: parseEventStream found totalTokens in messageMetadataEvent: %d", usageInfo.TotalTokens)
}
}
case "usageEvent", "usage":
// Handle dedicated usage events
if inputTokens, ok := event["inputTokens"].(float64); ok {
usageInfo.InputTokens = int64(inputTokens)
log.Debugf("kiro: parseEventStream found inputTokens in usageEvent: %d", usageInfo.InputTokens)
}
if outputTokens, ok := event["outputTokens"].(float64); ok {
usageInfo.OutputTokens = int64(outputTokens)
log.Debugf("kiro: parseEventStream found outputTokens in usageEvent: %d", usageInfo.OutputTokens)
}
if totalTokens, ok := event["totalTokens"].(float64); ok {
usageInfo.TotalTokens = int64(totalTokens)
log.Debugf("kiro: parseEventStream found totalTokens in usageEvent: %d", usageInfo.TotalTokens)
}
// Also check nested usage object
if usageObj, ok := event["usage"].(map[string]interface{}); ok {
if inputTokens, ok := usageObj["input_tokens"].(float64); ok {
usageInfo.InputTokens = int64(inputTokens)
} else if inputTokens, ok := usageObj["prompt_tokens"].(float64); ok {
usageInfo.InputTokens = int64(inputTokens)
}
if outputTokens, ok := usageObj["output_tokens"].(float64); ok {
usageInfo.OutputTokens = int64(outputTokens)
} else if outputTokens, ok := usageObj["completion_tokens"].(float64); ok {
usageInfo.OutputTokens = int64(outputTokens)
}
if totalTokens, ok := usageObj["total_tokens"].(float64); ok {
usageInfo.TotalTokens = int64(totalTokens)
}
log.Debugf("kiro: parseEventStream found usage object: input=%d, output=%d, total=%d",
usageInfo.InputTokens, usageInfo.OutputTokens, usageInfo.TotalTokens)
}
case "metricsEvent":
// Handle metrics events which may contain usage data
if metrics, ok := event["metricsEvent"].(map[string]interface{}); ok {
if inputTokens, ok := metrics["inputTokens"].(float64); ok {
usageInfo.InputTokens = int64(inputTokens)
}
if outputTokens, ok := metrics["outputTokens"].(float64); ok {
usageInfo.OutputTokens = int64(outputTokens)
}
log.Debugf("kiro: parseEventStream found metricsEvent: input=%d, output=%d",
usageInfo.InputTokens, usageInfo.OutputTokens)
}
case "meteringEvent":
// Handle metering events from Kiro API (usage billing information)
// Official format: { unit: string, unitPlural: string, usage: number }
if metering, ok := event["meteringEvent"].(map[string]interface{}); ok {
unit := ""
if u, ok := metering["unit"].(string); ok {
unit = u
}
usageVal := 0.0
if u, ok := metering["usage"].(float64); ok {
usageVal = u
}
log.Infof("kiro: parseEventStream received meteringEvent: usage=%.2f %s", usageVal, unit)
// Store metering info for potential billing/statistics purposes
// Note: This is separate from token counts - it's AWS billing units
} else {
// Try direct fields
unit := ""
if u, ok := event["unit"].(string); ok {
unit = u
}
usageVal := 0.0
if u, ok := event["usage"].(float64); ok {
usageVal = u
}
if unit != "" || usageVal > 0 {
log.Infof("kiro: parseEventStream received meteringEvent (direct): usage=%.2f %s", usageVal, unit)
}
}
case "error", "exception", "internalServerException", "invalidStateEvent":
// Handle error events from Kiro API stream
errMsg := ""
errType := eventType
// Try to extract error message from various formats
if msg, ok := event["message"].(string); ok {
errMsg = msg
} else if errObj, ok := event[eventType].(map[string]interface{}); ok {
if msg, ok := errObj["message"].(string); ok {
errMsg = msg
}
if t, ok := errObj["type"].(string); ok {
errType = t
}
} else if errObj, ok := event["error"].(map[string]interface{}); ok {
if msg, ok := errObj["message"].(string); ok {
errMsg = msg
}
if t, ok := errObj["type"].(string); ok {
errType = t
}
}
// Check for specific error reasons
if reason, ok := event["reason"].(string); ok {
errMsg = fmt.Sprintf("%s (reason: %s)", errMsg, reason)
}
log.Errorf("kiro: parseEventStream received error event: type=%s, message=%s", errType, errMsg)
// For invalidStateEvent, we may want to continue processing other events
if eventType == "invalidStateEvent" {
log.Warnf("kiro: invalidStateEvent received, continuing stream processing")
continue
}
// For other errors, return the error
if errMsg != "" {
return "", nil, usageInfo, stopReason, fmt.Errorf("kiro API error (%s): %s", errType, errMsg)
}
default:
// Check for contextUsagePercentage in any event
if ctxPct, ok := event["contextUsagePercentage"].(float64); ok {
upstreamContextPercentage = ctxPct
log.Debugf("kiro: parseEventStream received context usage: %.2f%%", upstreamContextPercentage)
}
// Log unknown event types for debugging (to discover new event formats)
log.Debugf("kiro: parseEventStream unknown event type: %s, payload: %s", eventType, string(payload))
}
// Check for direct token fields in any event (fallback)
if usageInfo.InputTokens == 0 {
if inputTokens, ok := event["inputTokens"].(float64); ok {
usageInfo.InputTokens = int64(inputTokens)
log.Debugf("kiro: parseEventStream found direct inputTokens: %d", usageInfo.InputTokens)
}
}
if usageInfo.OutputTokens == 0 {
if outputTokens, ok := event["outputTokens"].(float64); ok {
usageInfo.OutputTokens = int64(outputTokens)
log.Debugf("kiro: parseEventStream found direct outputTokens: %d", usageInfo.OutputTokens)
}
}
// Check for usage object in any event (OpenAI format)
if usageInfo.InputTokens == 0 || usageInfo.OutputTokens == 0 {
if usageObj, ok := event["usage"].(map[string]interface{}); ok {
if usageInfo.InputTokens == 0 {
if inputTokens, ok := usageObj["input_tokens"].(float64); ok {
usageInfo.InputTokens = int64(inputTokens)
} else if inputTokens, ok := usageObj["prompt_tokens"].(float64); ok {
usageInfo.InputTokens = int64(inputTokens)
}
}
if usageInfo.OutputTokens == 0 {
if outputTokens, ok := usageObj["output_tokens"].(float64); ok {
usageInfo.OutputTokens = int64(outputTokens)
} else if outputTokens, ok := usageObj["completion_tokens"].(float64); ok {
usageInfo.OutputTokens = int64(outputTokens)
}
}
if usageInfo.TotalTokens == 0 {
if totalTokens, ok := usageObj["total_tokens"].(float64); ok {
usageInfo.TotalTokens = int64(totalTokens)
}
}
log.Debugf("kiro: parseEventStream found usage object (fallback): input=%d, output=%d, total=%d",
usageInfo.InputTokens, usageInfo.OutputTokens, usageInfo.TotalTokens)
}
}
// Also check nested supplementaryWebLinksEvent
if usageEvent, ok := event["supplementaryWebLinksEvent"].(map[string]interface{}); ok {
if inputTokens, ok := usageEvent["inputTokens"].(float64); ok {
usageInfo.InputTokens = int64(inputTokens)
}
if outputTokens, ok := usageEvent["outputTokens"].(float64); ok {
usageInfo.OutputTokens = int64(outputTokens)
}
}
}
// Parse embedded tool calls from content (e.g., [Called tool_name with args: {...}])
contentStr := content.String()
cleanedContent, embeddedToolUses := kiroclaude.ParseEmbeddedToolCalls(contentStr, processedIDs)
toolUses = append(toolUses, embeddedToolUses...)
// Deduplicate all tool uses
toolUses = kiroclaude.DeduplicateToolUses(toolUses)
// Apply fallback logic for stop_reason if not provided by upstream
// Priority: upstream stopReason > tool_use detection > end_turn default
if stopReason == "" {
if len(toolUses) > 0 {
stopReason = "tool_use"
log.Debugf("kiro: parseEventStream using fallback stop_reason: tool_use (detected %d tool uses)", len(toolUses))
} else {
stopReason = "end_turn"
log.Debugf("kiro: parseEventStream using fallback stop_reason: end_turn")
}
}
// Log warning if response was truncated due to max_tokens
if stopReason == "max_tokens" {
log.Warnf("kiro: response truncated due to max_tokens limit")
}
// Use contextUsagePercentage to calculate more accurate input tokens
// Kiro model has 200k max context, contextUsagePercentage represents the percentage used
// Formula: input_tokens = contextUsagePercentage * 200000 / 100
if upstreamContextPercentage > 0 {
calculatedInputTokens := int64(upstreamContextPercentage * 200000 / 100)
if calculatedInputTokens > 0 {
localEstimate := usageInfo.InputTokens
usageInfo.InputTokens = calculatedInputTokens
usageInfo.TotalTokens = usageInfo.InputTokens + usageInfo.OutputTokens
log.Infof("kiro: parseEventStream using contextUsagePercentage (%.2f%%) to calculate input tokens: %d (local estimate was: %d)",
upstreamContextPercentage, calculatedInputTokens, localEstimate)
}
}
return cleanedContent, toolUses, usageInfo, stopReason, nil
}
// readEventStreamMessage reads and validates a single AWS Event Stream message.
// Returns the parsed message or a structured error for different failure modes.
// This function implements boundary protection and detailed error classification.
//
// AWS Event Stream binary format:
// - Prelude (12 bytes): total_length (4) + headers_length (4) + prelude_crc (4)
// - Headers (variable): header entries
// - Payload (variable): JSON data
// - Message CRC (4 bytes): CRC32C of entire message (not validated, just skipped)
func (e *KiroExecutor) readEventStreamMessage(reader *bufio.Reader) (*eventStreamMessage, *EventStreamError) {
// Read prelude (first 12 bytes: total_len + headers_len + prelude_crc)
prelude := make([]byte, 12)
_, err := io.ReadFull(reader, prelude)
if err == io.EOF {
return nil, nil // Normal end of stream
}
if err != nil {
return nil, &EventStreamError{
Type: ErrStreamFatal,
Message: "failed to read prelude",
Cause: err,
}
}
totalLength := binary.BigEndian.Uint32(prelude[0:4])
headersLength := binary.BigEndian.Uint32(prelude[4:8])
// Note: prelude[8:12] is prelude_crc - we read it but don't validate (no CRC check per requirements)
// Boundary check: minimum frame size
if totalLength < minEventStreamFrameSize {
return nil, &EventStreamError{
Type: ErrStreamMalformed,
Message: fmt.Sprintf("invalid message length: %d (minimum is %d)", totalLength, minEventStreamFrameSize),
}
}
// Boundary check: maximum message size
if totalLength > maxEventStreamMsgSize {
return nil, &EventStreamError{
Type: ErrStreamMalformed,
Message: fmt.Sprintf("message too large: %d bytes (maximum is %d)", totalLength, maxEventStreamMsgSize),
}
}
// Boundary check: headers length within message bounds
// Message structure: prelude(12) + headers(headersLength) + payload + message_crc(4)
// So: headersLength must be <= totalLength - 16 (12 for prelude + 4 for message_crc)
if headersLength > totalLength-16 {
return nil, &EventStreamError{
Type: ErrStreamMalformed,
Message: fmt.Sprintf("headers length %d exceeds message bounds (total: %d)", headersLength, totalLength),
}
}
// Read the rest of the message (total - 12 bytes already read)
remaining := make([]byte, totalLength-12)
_, err = io.ReadFull(reader, remaining)
if err != nil {
return nil, &EventStreamError{
Type: ErrStreamFatal,
Message: "failed to read message body",
Cause: err,
}
}
// Extract event type from headers
// Headers start at beginning of 'remaining', length is headersLength
var eventType string
if headersLength > 0 && headersLength <= uint32(len(remaining)) {
eventType = e.extractEventTypeFromBytes(remaining[:headersLength])
}
// Calculate payload boundaries
// Payload starts after headers, ends before message_crc (last 4 bytes)
payloadStart := headersLength
payloadEnd := uint32(len(remaining)) - 4 // Skip message_crc at end
// Validate payload boundaries
if payloadStart >= payloadEnd {
// No payload, return empty message
return &eventStreamMessage{
EventType: eventType,
Payload: nil,
}, nil
}
payload := remaining[payloadStart:payloadEnd]
return &eventStreamMessage{
EventType: eventType,
Payload: payload,
}, nil
}
func skipEventStreamHeaderValue(headers []byte, offset int, valueType byte) (int, bool) {
switch valueType {
case 0, 1: // bool true / bool false
return offset, true
case 2: // byte
if offset+1 > len(headers) {
return offset, false
}
return offset + 1, true
case 3: // short
if offset+2 > len(headers) {
return offset, false
}
return offset + 2, true
case 4: // int
if offset+4 > len(headers) {
return offset, false
}
return offset + 4, true
case 5: // long
if offset+8 > len(headers) {
return offset, false
}
return offset + 8, true
case 6: // byte array (2-byte length + data)
if offset+2 > len(headers) {
return offset, false
}
valueLen := int(binary.BigEndian.Uint16(headers[offset : offset+2]))
offset += 2
if offset+valueLen > len(headers) {
return offset, false
}
return offset + valueLen, true
case 8: // timestamp
if offset+8 > len(headers) {
return offset, false
}
return offset + 8, true
case 9: // uuid
if offset+16 > len(headers) {
return offset, false
}
return offset + 16, true
default:
return offset, false
}
}
// extractEventTypeFromBytes extracts the event type from raw header bytes (without prelude CRC prefix)
func (e *KiroExecutor) extractEventTypeFromBytes(headers []byte) string {
offset := 0
for offset < len(headers) {
nameLen := int(headers[offset])
offset++
if offset+nameLen > len(headers) {
break
}
name := string(headers[offset : offset+nameLen])
offset += nameLen
if offset >= len(headers) {
break
}
valueType := headers[offset]
offset++
if valueType == 7 { // String type
if offset+2 > len(headers) {
break
}
valueLen := int(binary.BigEndian.Uint16(headers[offset : offset+2]))
offset += 2
if offset+valueLen > len(headers) {
break
}
value := string(headers[offset : offset+valueLen])
offset += valueLen
if name == ":event-type" {
return value
}
continue
}
nextOffset, ok := skipEventStreamHeaderValue(headers, offset, valueType)
if !ok {
break
}
offset = nextOffset
}
return ""
}
// NOTE: Response building functions moved to internal/translator/kiro/claude/kiro_claude_response.go
// The executor now uses kiroclaude.BuildClaudeResponse() and kiroclaude.ExtractThinkingFromContent() instead
// streamToChannel converts AWS Event Stream to channel-based streaming.
// Supports tool calling - emits tool_use content blocks when tools are used.
// Includes embedded [Called ...] tool call parsing and input buffering for toolUseEvent.
// Implements duplicate content filtering using lastContentEvent detection (based on AIClient-2-API).
// Extracts stop_reason from upstream events when available.
// thinkingEnabled controls whether <thinking> tags are parsed - only parse when request enabled thinking.
func (e *KiroExecutor) streamToChannel(ctx context.Context, body io.Reader, out chan<- cliproxyexecutor.StreamChunk, targetFormat sdktranslator.Format, model string, originalReq, claudeBody []byte, reporter *usageReporter, thinkingEnabled bool) {
reader := bufio.NewReaderSize(body, 20*1024*1024) // 20MB buffer to match other providers
var totalUsage usage.Detail
var hasToolUses bool // Track if any tool uses were emitted
var upstreamStopReason string // Track stop_reason from upstream events
// Tool use state tracking for input buffering and deduplication
processedIDs := make(map[string]bool)
var currentToolUse *kiroclaude.ToolUseState
// NOTE: Duplicate content filtering removed - it was causing legitimate repeated
// content (like consecutive newlines) to be incorrectly filtered out.
// The previous implementation compared lastContentEvent == contentDelta which
// is too aggressive for streaming scenarios.
// Streaming token calculation - accumulate content for real-time token counting
// Based on AIClient-2-API implementation
var accumulatedContent strings.Builder
accumulatedContent.Grow(4096) // Pre-allocate 4KB capacity to reduce reallocations
// Real-time usage estimation state
// These track when to send periodic usage updates during streaming
var lastUsageUpdateLen int // Last accumulated content length when usage was sent
var lastUsageUpdateTime = time.Now() // Last time usage update was sent
var lastReportedOutputTokens int64 // Last reported output token count
// Upstream usage tracking - Kiro API returns credit usage and context percentage
var upstreamCreditUsage float64 // Credit usage from upstream (e.g., 1.458)
var upstreamContextPercentage float64 // Context usage percentage from upstream (e.g., 78.56)
var hasUpstreamUsage bool // Whether we received usage from upstream
// Translator param for maintaining tool call state across streaming events
// IMPORTANT: This must persist across all TranslateStream calls
var translatorParam any
// Thinking mode state tracking - tag-based parsing for <thinking> tags in content
inThinkBlock := false // Whether we're currently inside a <thinking> block
isThinkingBlockOpen := false // Track if thinking content block SSE event is open
thinkingBlockIndex := -1 // Index of the thinking content block
var accumulatedThinkingContent strings.Builder // Accumulate thinking content for token counting
// Buffer for handling partial tag matches at chunk boundaries
var pendingContent strings.Builder // Buffer content that might be part of a tag
// Pre-calculate input tokens from request if possible
// Kiro uses Claude format, so try Claude format first, then OpenAI format, then fallback
if enc, err := getTokenizer(model); err == nil {
var inputTokens int64
var countMethod string
// Try Claude format first (Kiro uses Claude API format)
if inp, err := countClaudeChatTokens(enc, claudeBody); err == nil && inp > 0 {
inputTokens = inp
countMethod = "claude"
} else if inp, err := countOpenAIChatTokens(enc, originalReq); err == nil && inp > 0 {
// Fallback to OpenAI format (for OpenAI-compatible requests)
inputTokens = inp
countMethod = "openai"
} else {
// Final fallback: estimate from raw request size (roughly 4 chars per token)
inputTokens = int64(len(claudeBody) / 4)
if inputTokens == 0 && len(claudeBody) > 0 {
inputTokens = 1
}
countMethod = "estimate"
}
totalUsage.InputTokens = inputTokens
log.Debugf("kiro: streamToChannel pre-calculated input tokens: %d (method: %s, claude body: %d bytes, original req: %d bytes)",
totalUsage.InputTokens, countMethod, len(claudeBody), len(originalReq))
}
contentBlockIndex := -1
messageStartSent := false
isTextBlockOpen := false
var outputLen int
// Ensure usage is published even on early return
defer func() {
reporter.publish(ctx, totalUsage)
}()
for {
select {
case <-ctx.Done():
return
default:
}
msg, eventErr := e.readEventStreamMessage(reader)
if eventErr != nil {
// Log the error
log.Errorf("kiro: streamToChannel error: %v", eventErr)
// Send error to channel for client notification
out <- cliproxyexecutor.StreamChunk{Err: eventErr}
return
}
if msg == nil {
// Normal end of stream (EOF)
// Flush any incomplete tool use before ending stream
if currentToolUse != nil && !processedIDs[currentToolUse.ToolUseID] {
log.Warnf("kiro: flushing incomplete tool use at EOF: %s (ID: %s)", currentToolUse.Name, currentToolUse.ToolUseID)
fullInput := currentToolUse.InputBuffer.String()
repairedJSON := kiroclaude.RepairJSON(fullInput)
var finalInput map[string]interface{}
if err := json.Unmarshal([]byte(repairedJSON), &finalInput); err != nil {
log.Warnf("kiro: failed to parse incomplete tool input at EOF: %v", err)
finalInput = make(map[string]interface{})
}
processedIDs[currentToolUse.ToolUseID] = true
contentBlockIndex++
// Send tool_use content block
blockStart := kiroclaude.BuildClaudeContentBlockStartEvent(contentBlockIndex, "tool_use", currentToolUse.ToolUseID, currentToolUse.Name)
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, blockStart, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
// Send tool input as delta
inputBytes, _ := json.Marshal(finalInput)
inputDelta := kiroclaude.BuildClaudeInputJsonDeltaEvent(string(inputBytes), contentBlockIndex)
sseData = sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, inputDelta, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
// Close block
blockStop := kiroclaude.BuildClaudeContentBlockStopEvent(contentBlockIndex)
sseData = sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, blockStop, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
hasToolUses = true
currentToolUse = nil
}
// DISABLED: Tag-based pending character flushing
// This code block was used for tag-based thinking detection which has been
// replaced by reasoningContentEvent handling. No pending tag chars to flush.
// Original code preserved in git history.
break
}
eventType := msg.EventType
payload := msg.Payload
if len(payload) == 0 {
continue
}
appendAPIResponseChunk(ctx, e.cfg, payload)
var event map[string]interface{}
if err := json.Unmarshal(payload, &event); err != nil {
log.Warnf("kiro: failed to unmarshal event payload: %v, raw: %s", err, string(payload))
continue
}
// Check for error/exception events in the payload (Kiro API may return errors with HTTP 200)
// These can appear as top-level fields or nested within the event
if errType, hasErrType := event["_type"].(string); hasErrType {
// AWS-style error: {"_type": "com.amazon.aws.codewhisperer#ValidationException", "message": "..."}
errMsg := ""
if msg, ok := event["message"].(string); ok {
errMsg = msg
}
log.Errorf("kiro: received AWS error in stream: type=%s, message=%s", errType, errMsg)
out <- cliproxyexecutor.StreamChunk{Err: fmt.Errorf("kiro API error: %s - %s", errType, errMsg)}
return
}
if errType, hasErrType := event["type"].(string); hasErrType && (errType == "error" || errType == "exception") {
// Generic error event
errMsg := ""
if msg, ok := event["message"].(string); ok {
errMsg = msg
} else if errObj, ok := event["error"].(map[string]interface{}); ok {
if msg, ok := errObj["message"].(string); ok {
errMsg = msg
}
}
log.Errorf("kiro: received error event in stream: type=%s, message=%s", errType, errMsg)
out <- cliproxyexecutor.StreamChunk{Err: fmt.Errorf("kiro API error: %s", errMsg)}
return
}
// Extract stop_reason from various event formats (streaming)
// Kiro/Amazon Q API may include stop_reason in different locations
if sr := kirocommon.GetString(event, "stop_reason"); sr != "" {
upstreamStopReason = sr
log.Debugf("kiro: streamToChannel found stop_reason (top-level): %s", upstreamStopReason)
}
if sr := kirocommon.GetString(event, "stopReason"); sr != "" {
upstreamStopReason = sr
log.Debugf("kiro: streamToChannel found stopReason (top-level): %s", upstreamStopReason)
}
// Send message_start on first event
if !messageStartSent {
msgStart := kiroclaude.BuildClaudeMessageStartEvent(model, totalUsage.InputTokens)
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, msgStart, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
messageStartSent = true
}
switch eventType {
case "followupPromptEvent":
// Filter out followupPrompt events - these are UI suggestions, not content
log.Debugf("kiro: streamToChannel ignoring followupPrompt event")
continue
case "messageStopEvent", "message_stop":
// Handle message stop events which may contain stop_reason
if sr := kirocommon.GetString(event, "stop_reason"); sr != "" {
upstreamStopReason = sr
log.Debugf("kiro: streamToChannel found stop_reason in messageStopEvent: %s", upstreamStopReason)
}
if sr := kirocommon.GetString(event, "stopReason"); sr != "" {
upstreamStopReason = sr
log.Debugf("kiro: streamToChannel found stopReason in messageStopEvent: %s", upstreamStopReason)
}
case "meteringEvent":
// Handle metering events from Kiro API (usage billing information)
// Official format: { unit: string, unitPlural: string, usage: number }
if metering, ok := event["meteringEvent"].(map[string]interface{}); ok {
unit := ""
if u, ok := metering["unit"].(string); ok {
unit = u
}
usageVal := 0.0
if u, ok := metering["usage"].(float64); ok {
usageVal = u
}
upstreamCreditUsage = usageVal
hasUpstreamUsage = true
log.Infof("kiro: streamToChannel received meteringEvent: usage=%.4f %s", usageVal, unit)
} else {
// Try direct fields (event is meteringEvent itself)
if unit, ok := event["unit"].(string); ok {
if usage, ok := event["usage"].(float64); ok {
upstreamCreditUsage = usage
hasUpstreamUsage = true
log.Infof("kiro: streamToChannel received meteringEvent (direct): usage=%.4f %s", usage, unit)
}
}
}
case "error", "exception", "internalServerException":
// Handle error events from Kiro API stream
errMsg := ""
errType := eventType
// Try to extract error message from various formats
if msg, ok := event["message"].(string); ok {
errMsg = msg
} else if errObj, ok := event[eventType].(map[string]interface{}); ok {
if msg, ok := errObj["message"].(string); ok {
errMsg = msg
}
if t, ok := errObj["type"].(string); ok {
errType = t
}
} else if errObj, ok := event["error"].(map[string]interface{}); ok {
if msg, ok := errObj["message"].(string); ok {
errMsg = msg
}
}
log.Errorf("kiro: streamToChannel received error event: type=%s, message=%s", errType, errMsg)
// Send error to the stream and exit
if errMsg != "" {
out <- cliproxyexecutor.StreamChunk{
Err: fmt.Errorf("kiro API error (%s): %s", errType, errMsg),
}
return
}
case "invalidStateEvent":
// Handle invalid state events - log and continue (non-fatal)
errMsg := ""
if msg, ok := event["message"].(string); ok {
errMsg = msg
} else if stateEvent, ok := event["invalidStateEvent"].(map[string]interface{}); ok {
if msg, ok := stateEvent["message"].(string); ok {
errMsg = msg
}
}
log.Warnf("kiro: streamToChannel received invalidStateEvent: %s, continuing", errMsg)
continue
default:
// Check for upstream usage events from Kiro API
// Format: {"unit":"credit","unitPlural":"credits","usage":1.458}
if unit, ok := event["unit"].(string); ok && unit == "credit" {
if usage, ok := event["usage"].(float64); ok {
upstreamCreditUsage = usage
hasUpstreamUsage = true
log.Debugf("kiro: received upstream credit usage: %.4f", upstreamCreditUsage)
}
}
// Format: {"contextUsagePercentage":78.56}
if ctxPct, ok := event["contextUsagePercentage"].(float64); ok {
upstreamContextPercentage = ctxPct
log.Debugf("kiro: received upstream context usage: %.2f%%", upstreamContextPercentage)
}
// Check for token counts in unknown events
if inputTokens, ok := event["inputTokens"].(float64); ok {
totalUsage.InputTokens = int64(inputTokens)
hasUpstreamUsage = true
log.Debugf("kiro: streamToChannel found inputTokens in event %s: %d", eventType, totalUsage.InputTokens)
}
if outputTokens, ok := event["outputTokens"].(float64); ok {
totalUsage.OutputTokens = int64(outputTokens)
hasUpstreamUsage = true
log.Debugf("kiro: streamToChannel found outputTokens in event %s: %d", eventType, totalUsage.OutputTokens)
}
if totalTokens, ok := event["totalTokens"].(float64); ok {
totalUsage.TotalTokens = int64(totalTokens)
log.Debugf("kiro: streamToChannel found totalTokens in event %s: %d", eventType, totalUsage.TotalTokens)
}
// Check for usage object in unknown events (OpenAI/Claude format)
if usageObj, ok := event["usage"].(map[string]interface{}); ok {
if inputTokens, ok := usageObj["input_tokens"].(float64); ok {
totalUsage.InputTokens = int64(inputTokens)
hasUpstreamUsage = true
} else if inputTokens, ok := usageObj["prompt_tokens"].(float64); ok {
totalUsage.InputTokens = int64(inputTokens)
hasUpstreamUsage = true
}
if outputTokens, ok := usageObj["output_tokens"].(float64); ok {
totalUsage.OutputTokens = int64(outputTokens)
hasUpstreamUsage = true
} else if outputTokens, ok := usageObj["completion_tokens"].(float64); ok {
totalUsage.OutputTokens = int64(outputTokens)
hasUpstreamUsage = true
}
if totalTokens, ok := usageObj["total_tokens"].(float64); ok {
totalUsage.TotalTokens = int64(totalTokens)
}
log.Debugf("kiro: streamToChannel found usage object in event %s: input=%d, output=%d, total=%d",
eventType, totalUsage.InputTokens, totalUsage.OutputTokens, totalUsage.TotalTokens)
}
// Log unknown event types for debugging (to discover new event formats)
if eventType != "" {
log.Debugf("kiro: streamToChannel unknown event type: %s, payload: %s", eventType, string(payload))
}
case "assistantResponseEvent":
var contentDelta string
var toolUses []map[string]interface{}
if assistantResp, ok := event["assistantResponseEvent"].(map[string]interface{}); ok {
if c, ok := assistantResp["content"].(string); ok {
contentDelta = c
}
// Extract stop_reason from assistantResponseEvent
if sr := kirocommon.GetString(assistantResp, "stop_reason"); sr != "" {
upstreamStopReason = sr
log.Debugf("kiro: streamToChannel found stop_reason in assistantResponseEvent: %s", upstreamStopReason)
}
if sr := kirocommon.GetString(assistantResp, "stopReason"); sr != "" {
upstreamStopReason = sr
log.Debugf("kiro: streamToChannel found stopReason in assistantResponseEvent: %s", upstreamStopReason)
}
// Extract tool uses from response
if tus, ok := assistantResp["toolUses"].([]interface{}); ok {
for _, tuRaw := range tus {
if tu, ok := tuRaw.(map[string]interface{}); ok {
toolUses = append(toolUses, tu)
}
}
}
}
if contentDelta == "" {
if c, ok := event["content"].(string); ok {
contentDelta = c
}
}
// Direct tool uses
if tus, ok := event["toolUses"].([]interface{}); ok {
for _, tuRaw := range tus {
if tu, ok := tuRaw.(map[string]interface{}); ok {
toolUses = append(toolUses, tu)
}
}
}
// Handle text content with thinking mode support
if contentDelta != "" {
// NOTE: Duplicate content filtering was removed because it incorrectly
// filtered out legitimate repeated content (like consecutive newlines "\n\n").
// Streaming naturally can have identical chunks that are valid content.
outputLen += len(contentDelta)
// Accumulate content for streaming token calculation
accumulatedContent.WriteString(contentDelta)
// Real-time usage estimation: Check if we should send a usage update
// This helps clients track context usage during long thinking sessions
shouldSendUsageUpdate := false
if accumulatedContent.Len()-lastUsageUpdateLen >= usageUpdateCharThreshold {
shouldSendUsageUpdate = true
} else if time.Since(lastUsageUpdateTime) >= usageUpdateTimeInterval && accumulatedContent.Len() > lastUsageUpdateLen {
shouldSendUsageUpdate = true
}
if shouldSendUsageUpdate {
// Calculate current output tokens using tiktoken
var currentOutputTokens int64
if enc, encErr := getTokenizer(model); encErr == nil {
if tokenCount, countErr := enc.Count(accumulatedContent.String()); countErr == nil {
currentOutputTokens = int64(tokenCount)
}
}
// Fallback to character estimation if tiktoken fails
if currentOutputTokens == 0 {
currentOutputTokens = int64(accumulatedContent.Len() / 4)
if currentOutputTokens == 0 {
currentOutputTokens = 1
}
}
// Only send update if token count has changed significantly (at least 10 tokens)
if currentOutputTokens > lastReportedOutputTokens+10 {
// Send ping event with usage information
// This is a non-blocking update that clients can optionally process
pingEvent := kiroclaude.BuildClaudePingEventWithUsage(totalUsage.InputTokens, currentOutputTokens)
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, pingEvent, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
lastReportedOutputTokens = currentOutputTokens
log.Debugf("kiro: sent real-time usage update - input: %d, output: %d (accumulated: %d chars)",
totalUsage.InputTokens, currentOutputTokens, accumulatedContent.Len())
}
lastUsageUpdateLen = accumulatedContent.Len()
lastUsageUpdateTime = time.Now()
}
// TAG-BASED THINKING PARSING: Parse <thinking> tags from content
// Combine pending content with new content for processing
pendingContent.WriteString(contentDelta)
processContent := pendingContent.String()
pendingContent.Reset()
// Process content looking for thinking tags
for len(processContent) > 0 {
if inThinkBlock {
// We're inside a thinking block, look for </thinking>
endIdx := strings.Index(processContent, kirocommon.ThinkingEndTag)
if endIdx >= 0 {
// Found end tag - emit thinking content before the tag
thinkingText := processContent[:endIdx]
if thinkingText != "" {
// Ensure thinking block is open
if !isThinkingBlockOpen {
contentBlockIndex++
thinkingBlockIndex = contentBlockIndex
isThinkingBlockOpen = true
blockStart := kiroclaude.BuildClaudeContentBlockStartEvent(thinkingBlockIndex, "thinking", "", "")
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, blockStart, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
}
// Send thinking delta
thinkingEvent := kiroclaude.BuildClaudeThinkingDeltaEvent(thinkingText, thinkingBlockIndex)
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, thinkingEvent, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
accumulatedThinkingContent.WriteString(thinkingText)
}
// Close thinking block
if isThinkingBlockOpen {
blockStop := kiroclaude.BuildClaudeThinkingBlockStopEvent(thinkingBlockIndex)
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, blockStop, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
isThinkingBlockOpen = false
}
inThinkBlock = false
processContent = processContent[endIdx+len(kirocommon.ThinkingEndTag):]
log.Debugf("kiro: closed thinking block, remaining content: %d chars", len(processContent))
} else {
// No end tag found - check for partial match at end
partialMatch := false
for i := 1; i < len(kirocommon.ThinkingEndTag) && i <= len(processContent); i++ {
if strings.HasSuffix(processContent, kirocommon.ThinkingEndTag[:i]) {
// Possible partial tag at end, buffer it
pendingContent.WriteString(processContent[len(processContent)-i:])
processContent = processContent[:len(processContent)-i]
partialMatch = true
break
}
}
if !partialMatch || len(processContent) > 0 {
// Emit all as thinking content
if processContent != "" {
if !isThinkingBlockOpen {
contentBlockIndex++
thinkingBlockIndex = contentBlockIndex
isThinkingBlockOpen = true
blockStart := kiroclaude.BuildClaudeContentBlockStartEvent(thinkingBlockIndex, "thinking", "", "")
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, blockStart, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
}
thinkingEvent := kiroclaude.BuildClaudeThinkingDeltaEvent(processContent, thinkingBlockIndex)
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, thinkingEvent, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
accumulatedThinkingContent.WriteString(processContent)
}
}
processContent = ""
}
} else {
// Not in thinking block, look for <thinking>
startIdx := strings.Index(processContent, kirocommon.ThinkingStartTag)
if startIdx >= 0 {
// Found start tag - emit text content before the tag
textBefore := processContent[:startIdx]
if textBefore != "" {
// Close thinking block if open
if isThinkingBlockOpen {
blockStop := kiroclaude.BuildClaudeThinkingBlockStopEvent(thinkingBlockIndex)
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, blockStop, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
isThinkingBlockOpen = false
}
// Ensure text block is open
if !isTextBlockOpen {
contentBlockIndex++
isTextBlockOpen = true
blockStart := kiroclaude.BuildClaudeContentBlockStartEvent(contentBlockIndex, "text", "", "")
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, blockStart, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
}
// Send text delta
claudeEvent := kiroclaude.BuildClaudeStreamEvent(textBefore, contentBlockIndex)
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, claudeEvent, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
}
// Close text block before entering thinking
if isTextBlockOpen {
blockStop := kiroclaude.BuildClaudeContentBlockStopEvent(contentBlockIndex)
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, blockStop, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
isTextBlockOpen = false
}
inThinkBlock = true
processContent = processContent[startIdx+len(kirocommon.ThinkingStartTag):]
log.Debugf("kiro: entered thinking block")
} else {
// No start tag found - check for partial match at end
partialMatch := false
for i := 1; i < len(kirocommon.ThinkingStartTag) && i <= len(processContent); i++ {
if strings.HasSuffix(processContent, kirocommon.ThinkingStartTag[:i]) {
// Possible partial tag at end, buffer it
pendingContent.WriteString(processContent[len(processContent)-i:])
processContent = processContent[:len(processContent)-i]
partialMatch = true
break
}
}
if !partialMatch || len(processContent) > 0 {
// Emit all as text content
if processContent != "" {
if !isTextBlockOpen {
contentBlockIndex++
isTextBlockOpen = true
blockStart := kiroclaude.BuildClaudeContentBlockStartEvent(contentBlockIndex, "text", "", "")
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, blockStart, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
}
claudeEvent := kiroclaude.BuildClaudeStreamEvent(processContent, contentBlockIndex)
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, claudeEvent, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
}
}
processContent = ""
}
}
}
}
// Handle tool uses in response (with deduplication)
for _, tu := range toolUses {
toolUseID := kirocommon.GetString(tu, "toolUseId")
toolName := kirocommon.GetString(tu, "name")
// Check for duplicate
if processedIDs[toolUseID] {
log.Debugf("kiro: skipping duplicate tool use in stream: %s", toolUseID)
continue
}
processedIDs[toolUseID] = true
hasToolUses = true
// Close text block if open before starting tool_use block
if isTextBlockOpen && contentBlockIndex >= 0 {
blockStop := kiroclaude.BuildClaudeContentBlockStopEvent(contentBlockIndex)
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, blockStop, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
isTextBlockOpen = false
}
// Emit tool_use content block
contentBlockIndex++
blockStart := kiroclaude.BuildClaudeContentBlockStartEvent(contentBlockIndex, "tool_use", toolUseID, toolName)
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, blockStart, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
// Send input_json_delta with the tool input
if input, ok := tu["input"].(map[string]interface{}); ok {
inputJSON, err := json.Marshal(input)
if err != nil {
log.Debugf("kiro: failed to marshal tool input: %v", err)
// Don't continue - still need to close the block
} else {
inputDelta := kiroclaude.BuildClaudeInputJsonDeltaEvent(string(inputJSON), contentBlockIndex)
sseData = sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, inputDelta, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
}
}
// Close tool_use block (always close even if input marshal failed)
blockStop := kiroclaude.BuildClaudeContentBlockStopEvent(contentBlockIndex)
sseData = sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, blockStop, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
}
case "reasoningContentEvent":
// Handle official reasoningContentEvent from Kiro API
// This replaces tag-based thinking detection with the proper event type
// Official format: { text: string, signature?: string, redactedContent?: base64 }
var thinkingText string
var signature string
if re, ok := event["reasoningContentEvent"].(map[string]interface{}); ok {
if text, ok := re["text"].(string); ok {
thinkingText = text
}
if sig, ok := re["signature"].(string); ok {
signature = sig
if len(sig) > 20 {
log.Debugf("kiro: reasoningContentEvent has signature: %s...", sig[:20])
} else {
log.Debugf("kiro: reasoningContentEvent has signature: %s", sig)
}
}
} else {
// Try direct fields
if text, ok := event["text"].(string); ok {
thinkingText = text
}
if sig, ok := event["signature"].(string); ok {
signature = sig
}
}
if thinkingText != "" {
// Close text block if open before starting thinking block
if isTextBlockOpen && contentBlockIndex >= 0 {
blockStop := kiroclaude.BuildClaudeContentBlockStopEvent(contentBlockIndex)
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, blockStop, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
isTextBlockOpen = false
}
// Start thinking block if not already open
if !isThinkingBlockOpen {
contentBlockIndex++
thinkingBlockIndex = contentBlockIndex
isThinkingBlockOpen = true
blockStart := kiroclaude.BuildClaudeContentBlockStartEvent(thinkingBlockIndex, "thinking", "", "")
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, blockStart, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
}
// Send thinking content
thinkingEvent := kiroclaude.BuildClaudeThinkingDeltaEvent(thinkingText, thinkingBlockIndex)
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, thinkingEvent, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
// Accumulate for token counting
accumulatedThinkingContent.WriteString(thinkingText)
log.Debugf("kiro: received reasoningContentEvent, text length: %d, has signature: %v", len(thinkingText), signature != "")
}
// Note: We don't close the thinking block here - it will be closed when we see
// the next assistantResponseEvent or at the end of the stream
_ = signature // Signature can be used for verification if needed
case "toolUseEvent":
// Handle dedicated tool use events with input buffering
completedToolUses, newState := kiroclaude.ProcessToolUseEvent(event, currentToolUse, processedIDs)
currentToolUse = newState
// Emit completed tool uses
for _, tu := range completedToolUses {
hasToolUses = true
// Close text block if open
if isTextBlockOpen && contentBlockIndex >= 0 {
blockStop := kiroclaude.BuildClaudeContentBlockStopEvent(contentBlockIndex)
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, blockStop, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
isTextBlockOpen = false
}
contentBlockIndex++
blockStart := kiroclaude.BuildClaudeContentBlockStartEvent(contentBlockIndex, "tool_use", tu.ToolUseID, tu.Name)
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, blockStart, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
if tu.Input != nil {
inputJSON, err := json.Marshal(tu.Input)
if err != nil {
log.Debugf("kiro: failed to marshal tool input in toolUseEvent: %v", err)
} else {
inputDelta := kiroclaude.BuildClaudeInputJsonDeltaEvent(string(inputJSON), contentBlockIndex)
sseData = sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, inputDelta, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
}
}
blockStop := kiroclaude.BuildClaudeContentBlockStopEvent(contentBlockIndex)
sseData = sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, blockStop, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
}
case "supplementaryWebLinksEvent":
if inputTokens, ok := event["inputTokens"].(float64); ok {
totalUsage.InputTokens = int64(inputTokens)
}
if outputTokens, ok := event["outputTokens"].(float64); ok {
totalUsage.OutputTokens = int64(outputTokens)
}
case "messageMetadataEvent", "metadataEvent":
// Handle message metadata events which contain token counts
// Official format: { tokenUsage: { outputTokens, totalTokens, uncachedInputTokens, cacheReadInputTokens, cacheWriteInputTokens, contextUsagePercentage } }
var metadata map[string]interface{}
if m, ok := event["messageMetadataEvent"].(map[string]interface{}); ok {
metadata = m
} else if m, ok := event["metadataEvent"].(map[string]interface{}); ok {
metadata = m
} else {
metadata = event // event itself might be the metadata
}
// Check for nested tokenUsage object (official format)
if tokenUsage, ok := metadata["tokenUsage"].(map[string]interface{}); ok {
// outputTokens - precise output token count
if outputTokens, ok := tokenUsage["outputTokens"].(float64); ok {
totalUsage.OutputTokens = int64(outputTokens)
hasUpstreamUsage = true
log.Infof("kiro: streamToChannel found precise outputTokens in tokenUsage: %d", totalUsage.OutputTokens)
}
// totalTokens - precise total token count
if totalTokens, ok := tokenUsage["totalTokens"].(float64); ok {
totalUsage.TotalTokens = int64(totalTokens)
log.Infof("kiro: streamToChannel found precise totalTokens in tokenUsage: %d", totalUsage.TotalTokens)
}
// uncachedInputTokens - input tokens not from cache
if uncachedInputTokens, ok := tokenUsage["uncachedInputTokens"].(float64); ok {
totalUsage.InputTokens = int64(uncachedInputTokens)
hasUpstreamUsage = true
log.Infof("kiro: streamToChannel found uncachedInputTokens in tokenUsage: %d", totalUsage.InputTokens)
}
// cacheReadInputTokens - tokens read from cache
if cacheReadTokens, ok := tokenUsage["cacheReadInputTokens"].(float64); ok {
// Add to input tokens if we have uncached tokens, otherwise use as input
if totalUsage.InputTokens > 0 {
totalUsage.InputTokens += int64(cacheReadTokens)
} else {
totalUsage.InputTokens = int64(cacheReadTokens)
}
hasUpstreamUsage = true
log.Debugf("kiro: streamToChannel found cacheReadInputTokens in tokenUsage: %d", int64(cacheReadTokens))
}
// contextUsagePercentage - can be used as fallback for input token estimation
if ctxPct, ok := tokenUsage["contextUsagePercentage"].(float64); ok {
upstreamContextPercentage = ctxPct
log.Debugf("kiro: streamToChannel found contextUsagePercentage in tokenUsage: %.2f%%", ctxPct)
}
}
// Fallback: check for direct fields in metadata (legacy format)
if totalUsage.InputTokens == 0 {
if inputTokens, ok := metadata["inputTokens"].(float64); ok {
totalUsage.InputTokens = int64(inputTokens)
hasUpstreamUsage = true
log.Debugf("kiro: streamToChannel found inputTokens in messageMetadataEvent: %d", totalUsage.InputTokens)
}
}
if totalUsage.OutputTokens == 0 {
if outputTokens, ok := metadata["outputTokens"].(float64); ok {
totalUsage.OutputTokens = int64(outputTokens)
hasUpstreamUsage = true
log.Debugf("kiro: streamToChannel found outputTokens in messageMetadataEvent: %d", totalUsage.OutputTokens)
}
}
if totalUsage.TotalTokens == 0 {
if totalTokens, ok := metadata["totalTokens"].(float64); ok {
totalUsage.TotalTokens = int64(totalTokens)
log.Debugf("kiro: streamToChannel found totalTokens in messageMetadataEvent: %d", totalUsage.TotalTokens)
}
}
case "usageEvent", "usage":
// Handle dedicated usage events
if inputTokens, ok := event["inputTokens"].(float64); ok {
totalUsage.InputTokens = int64(inputTokens)
log.Debugf("kiro: streamToChannel found inputTokens in usageEvent: %d", totalUsage.InputTokens)
}
if outputTokens, ok := event["outputTokens"].(float64); ok {
totalUsage.OutputTokens = int64(outputTokens)
log.Debugf("kiro: streamToChannel found outputTokens in usageEvent: %d", totalUsage.OutputTokens)
}
if totalTokens, ok := event["totalTokens"].(float64); ok {
totalUsage.TotalTokens = int64(totalTokens)
log.Debugf("kiro: streamToChannel found totalTokens in usageEvent: %d", totalUsage.TotalTokens)
}
// Also check nested usage object
if usageObj, ok := event["usage"].(map[string]interface{}); ok {
if inputTokens, ok := usageObj["input_tokens"].(float64); ok {
totalUsage.InputTokens = int64(inputTokens)
} else if inputTokens, ok := usageObj["prompt_tokens"].(float64); ok {
totalUsage.InputTokens = int64(inputTokens)
}
if outputTokens, ok := usageObj["output_tokens"].(float64); ok {
totalUsage.OutputTokens = int64(outputTokens)
} else if outputTokens, ok := usageObj["completion_tokens"].(float64); ok {
totalUsage.OutputTokens = int64(outputTokens)
}
if totalTokens, ok := usageObj["total_tokens"].(float64); ok {
totalUsage.TotalTokens = int64(totalTokens)
}
log.Debugf("kiro: streamToChannel found usage object: input=%d, output=%d, total=%d",
totalUsage.InputTokens, totalUsage.OutputTokens, totalUsage.TotalTokens)
}
case "metricsEvent":
// Handle metrics events which may contain usage data
if metrics, ok := event["metricsEvent"].(map[string]interface{}); ok {
if inputTokens, ok := metrics["inputTokens"].(float64); ok {
totalUsage.InputTokens = int64(inputTokens)
}
if outputTokens, ok := metrics["outputTokens"].(float64); ok {
totalUsage.OutputTokens = int64(outputTokens)
}
log.Debugf("kiro: streamToChannel found metricsEvent: input=%d, output=%d",
totalUsage.InputTokens, totalUsage.OutputTokens)
}
}
// Check nested usage event
if usageEvent, ok := event["supplementaryWebLinksEvent"].(map[string]interface{}); ok {
if inputTokens, ok := usageEvent["inputTokens"].(float64); ok {
totalUsage.InputTokens = int64(inputTokens)
}
if outputTokens, ok := usageEvent["outputTokens"].(float64); ok {
totalUsage.OutputTokens = int64(outputTokens)
}
}
// Check for direct token fields in any event (fallback)
if totalUsage.InputTokens == 0 {
if inputTokens, ok := event["inputTokens"].(float64); ok {
totalUsage.InputTokens = int64(inputTokens)
log.Debugf("kiro: streamToChannel found direct inputTokens: %d", totalUsage.InputTokens)
}
}
if totalUsage.OutputTokens == 0 {
if outputTokens, ok := event["outputTokens"].(float64); ok {
totalUsage.OutputTokens = int64(outputTokens)
log.Debugf("kiro: streamToChannel found direct outputTokens: %d", totalUsage.OutputTokens)
}
}
// Check for usage object in any event (OpenAI format)
if totalUsage.InputTokens == 0 || totalUsage.OutputTokens == 0 {
if usageObj, ok := event["usage"].(map[string]interface{}); ok {
if totalUsage.InputTokens == 0 {
if inputTokens, ok := usageObj["input_tokens"].(float64); ok {
totalUsage.InputTokens = int64(inputTokens)
} else if inputTokens, ok := usageObj["prompt_tokens"].(float64); ok {
totalUsage.InputTokens = int64(inputTokens)
}
}
if totalUsage.OutputTokens == 0 {
if outputTokens, ok := usageObj["output_tokens"].(float64); ok {
totalUsage.OutputTokens = int64(outputTokens)
} else if outputTokens, ok := usageObj["completion_tokens"].(float64); ok {
totalUsage.OutputTokens = int64(outputTokens)
}
}
if totalUsage.TotalTokens == 0 {
if totalTokens, ok := usageObj["total_tokens"].(float64); ok {
totalUsage.TotalTokens = int64(totalTokens)
}
}
log.Debugf("kiro: streamToChannel found usage object (fallback): input=%d, output=%d, total=%d",
totalUsage.InputTokens, totalUsage.OutputTokens, totalUsage.TotalTokens)
}
}
}
// Close content block if open
if isTextBlockOpen && contentBlockIndex >= 0 {
blockStop := kiroclaude.BuildClaudeContentBlockStopEvent(contentBlockIndex)
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, blockStop, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
}
// Streaming token calculation - calculate output tokens from accumulated content
// Only use local estimation if server didn't provide usage (server-side usage takes priority)
if totalUsage.OutputTokens == 0 && accumulatedContent.Len() > 0 {
// Try to use tiktoken for accurate counting
if enc, err := getTokenizer(model); err == nil {
if tokenCount, countErr := enc.Count(accumulatedContent.String()); countErr == nil {
totalUsage.OutputTokens = int64(tokenCount)
log.Debugf("kiro: streamToChannel calculated output tokens using tiktoken: %d", totalUsage.OutputTokens)
} else {
// Fallback on count error: estimate from character count
totalUsage.OutputTokens = int64(accumulatedContent.Len() / 4)
if totalUsage.OutputTokens == 0 {
totalUsage.OutputTokens = 1
}
log.Debugf("kiro: streamToChannel tiktoken count failed, estimated from chars: %d", totalUsage.OutputTokens)
}
} else {
// Fallback: estimate from character count (roughly 4 chars per token)
totalUsage.OutputTokens = int64(accumulatedContent.Len() / 4)
if totalUsage.OutputTokens == 0 {
totalUsage.OutputTokens = 1
}
log.Debugf("kiro: streamToChannel estimated output tokens from chars: %d (content len: %d)", totalUsage.OutputTokens, accumulatedContent.Len())
}
} else if totalUsage.OutputTokens == 0 && outputLen > 0 {
// Legacy fallback using outputLen
totalUsage.OutputTokens = int64(outputLen / 4)
if totalUsage.OutputTokens == 0 {
totalUsage.OutputTokens = 1
}
}
// Use contextUsagePercentage to calculate more accurate input tokens
// Kiro model has 200k max context, contextUsagePercentage represents the percentage used
// Formula: input_tokens = contextUsagePercentage * 200000 / 100
// Note: The effective input context is ~170k (200k - 30k reserved for output)
if upstreamContextPercentage > 0 {
// Calculate input tokens from context percentage
// Using 200k as the base since that's what Kiro reports against
calculatedInputTokens := int64(upstreamContextPercentage * 200000 / 100)
// Only use calculated value if it's significantly different from local estimate
// This provides more accurate token counts based on upstream data
if calculatedInputTokens > 0 {
localEstimate := totalUsage.InputTokens
totalUsage.InputTokens = calculatedInputTokens
log.Debugf("kiro: using contextUsagePercentage (%.2f%%) to calculate input tokens: %d (local estimate was: %d)",
upstreamContextPercentage, calculatedInputTokens, localEstimate)
}
}
totalUsage.TotalTokens = totalUsage.InputTokens + totalUsage.OutputTokens
// Log upstream usage information if received
if hasUpstreamUsage {
log.Debugf("kiro: upstream usage - credits: %.4f, context: %.2f%%, final tokens - input: %d, output: %d, total: %d",
upstreamCreditUsage, upstreamContextPercentage,
totalUsage.InputTokens, totalUsage.OutputTokens, totalUsage.TotalTokens)
}
// Determine stop reason: prefer upstream, then detect tool_use, default to end_turn
stopReason := upstreamStopReason
if stopReason == "" {
if hasToolUses {
stopReason = "tool_use"
log.Debugf("kiro: streamToChannel using fallback stop_reason: tool_use")
} else {
stopReason = "end_turn"
log.Debugf("kiro: streamToChannel using fallback stop_reason: end_turn")
}
}
// Log warning if response was truncated due to max_tokens
if stopReason == "max_tokens" {
log.Warnf("kiro: response truncated due to max_tokens limit (streamToChannel)")
}
// Send message_delta event
msgDelta := kiroclaude.BuildClaudeMessageDeltaEvent(stopReason, totalUsage)
sseData := sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, msgDelta, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
// Send message_stop event separately
msgStop := kiroclaude.BuildClaudeMessageStopOnlyEvent()
sseData = sdktranslator.TranslateStream(ctx, sdktranslator.FromString("kiro"), targetFormat, model, originalReq, claudeBody, msgStop, &translatorParam)
for _, chunk := range sseData {
if chunk != "" {
out <- cliproxyexecutor.StreamChunk{Payload: []byte(chunk + "\n\n")}
}
}
// reporter.publish is called via defer
}
// NOTE: Claude SSE event builders moved to internal/translator/kiro/claude/kiro_claude_stream.go
// The executor now uses kiroclaude.BuildClaude*Event() functions instead
// CountTokens counts tokens locally using tiktoken since Kiro API doesn't expose a token counting endpoint.
// This provides approximate token counts for client requests.
func (e *KiroExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error) {
// Use tiktoken for local token counting
enc, err := getTokenizer(req.Model)
if err != nil {
log.Warnf("kiro: CountTokens failed to get tokenizer: %v, falling back to estimate", err)
// Fallback: estimate from payload size (roughly 4 chars per token)
estimatedTokens := len(req.Payload) / 4
if estimatedTokens == 0 && len(req.Payload) > 0 {
estimatedTokens = 1
}
return cliproxyexecutor.Response{
Payload: []byte(fmt.Sprintf(`{"count":%d}`, estimatedTokens)),
}, nil
}
// Try to count tokens from the request payload
var totalTokens int64
// Try OpenAI chat format first
if tokens, countErr := countOpenAIChatTokens(enc, req.Payload); countErr == nil && tokens > 0 {
totalTokens = tokens
log.Debugf("kiro: CountTokens counted %d tokens using OpenAI chat format", totalTokens)
} else {
// Fallback: count raw payload tokens
if tokenCount, countErr := enc.Count(string(req.Payload)); countErr == nil {
totalTokens = int64(tokenCount)
log.Debugf("kiro: CountTokens counted %d tokens from raw payload", totalTokens)
} else {
// Final fallback: estimate from payload size
totalTokens = int64(len(req.Payload) / 4)
if totalTokens == 0 && len(req.Payload) > 0 {
totalTokens = 1
}
log.Debugf("kiro: CountTokens estimated %d tokens from payload size", totalTokens)
}
}
return cliproxyexecutor.Response{
Payload: []byte(fmt.Sprintf(`{"count":%d}`, totalTokens)),
}, nil
}
// Refresh refreshes the Kiro OAuth token.
// Supports both AWS Builder ID (SSO OIDC) and Google OAuth (social login).
// Uses mutex to prevent race conditions when multiple concurrent requests try to refresh.
func (e *KiroExecutor) Refresh(ctx context.Context, auth *cliproxyauth.Auth) (*cliproxyauth.Auth, error) {
// Serialize token refresh operations to prevent race conditions
e.refreshMu.Lock()
defer e.refreshMu.Unlock()
var authID string
if auth != nil {
authID = auth.ID
} else {
authID = "<nil>"
}
log.Debugf("kiro executor: refresh called for auth %s", authID)
if auth == nil {
return nil, fmt.Errorf("kiro executor: auth is nil")
}
// Double-check: After acquiring lock, verify token still needs refresh
// Another goroutine may have already refreshed while we were waiting
// NOTE: This check has a design limitation - it reads from the auth object passed in,
// not from persistent storage. If another goroutine returns a new Auth object (via Clone),
// this check won't see those updates. The mutex still prevents truly concurrent refreshes,
// but queued goroutines may still attempt redundant refreshes. This is acceptable as
// the refresh operation is idempotent and the extra API calls are infrequent.
if auth.Metadata != nil {
if lastRefresh, ok := auth.Metadata["last_refresh"].(string); ok {
if refreshTime, err := time.Parse(time.RFC3339, lastRefresh); err == nil {
// If token was refreshed within the last 30 seconds, skip refresh
if time.Since(refreshTime) < 30*time.Second {
log.Debugf("kiro executor: token was recently refreshed by another goroutine, skipping")
return auth, nil
}
}
}
// Also check if expires_at is now in the future with sufficient buffer
if expiresAt, ok := auth.Metadata["expires_at"].(string); ok {
if expTime, err := time.Parse(time.RFC3339, expiresAt); err == nil {
// If token expires more than 5 minutes from now, it's still valid
if time.Until(expTime) > 5*time.Minute {
log.Debugf("kiro executor: token is still valid (expires in %v), skipping refresh", time.Until(expTime))
// CRITICAL FIX: Set NextRefreshAfter to prevent frequent refresh checks
// Without this, shouldRefresh() will return true again in 5 seconds
updated := auth.Clone()
// Set next refresh to 5 minutes before expiry, or at least 30 seconds from now
nextRefresh := expTime.Add(-5 * time.Minute)
minNextRefresh := time.Now().Add(30 * time.Second)
if nextRefresh.Before(minNextRefresh) {
nextRefresh = minNextRefresh
}
updated.NextRefreshAfter = nextRefresh
log.Debugf("kiro executor: setting NextRefreshAfter to %v (in %v)", nextRefresh.Format(time.RFC3339), time.Until(nextRefresh))
return updated, nil
}
}
}
}
var refreshToken string
var clientID, clientSecret string
var authMethod string
var region, startURL string
if auth.Metadata != nil {
if rt, ok := auth.Metadata["refresh_token"].(string); ok {
refreshToken = rt
}
if cid, ok := auth.Metadata["client_id"].(string); ok {
clientID = cid
}
if cs, ok := auth.Metadata["client_secret"].(string); ok {
clientSecret = cs
}
if am, ok := auth.Metadata["auth_method"].(string); ok {
authMethod = am
}
if r, ok := auth.Metadata["region"].(string); ok {
region = r
}
if su, ok := auth.Metadata["start_url"].(string); ok {
startURL = su
}
}
if refreshToken == "" {
return nil, fmt.Errorf("kiro executor: refresh token not found")
}
var tokenData *kiroauth.KiroTokenData
var err error
ssoClient := kiroauth.NewSSOOIDCClient(e.cfg)
// Use SSO OIDC refresh for AWS Builder ID or IDC, otherwise use Kiro's OAuth refresh endpoint
switch {
case clientID != "" && clientSecret != "" && authMethod == "idc" && region != "":
// IDC refresh with region-specific endpoint
log.Debugf("kiro executor: using SSO OIDC refresh for IDC (region=%s)", region)
tokenData, err = ssoClient.RefreshTokenWithRegion(ctx, clientID, clientSecret, refreshToken, region, startURL)
case clientID != "" && clientSecret != "" && authMethod == "builder-id":
// Builder ID refresh with default endpoint
log.Debugf("kiro executor: using SSO OIDC refresh for AWS Builder ID")
tokenData, err = ssoClient.RefreshToken(ctx, clientID, clientSecret, refreshToken)
default:
// Fallback to Kiro's OAuth refresh endpoint (for social auth: Google/GitHub)
log.Debugf("kiro executor: using Kiro OAuth refresh endpoint")
oauth := kiroauth.NewKiroOAuth(e.cfg)
tokenData, err = oauth.RefreshToken(ctx, refreshToken)
}
if err != nil {
return nil, fmt.Errorf("kiro executor: token refresh failed: %w", err)
}
updated := auth.Clone()
now := time.Now()
updated.UpdatedAt = now
updated.LastRefreshedAt = now
if updated.Metadata == nil {
updated.Metadata = make(map[string]any)
}
updated.Metadata["access_token"] = tokenData.AccessToken
updated.Metadata["refresh_token"] = tokenData.RefreshToken
updated.Metadata["expires_at"] = tokenData.ExpiresAt
updated.Metadata["last_refresh"] = now.Format(time.RFC3339)
if tokenData.ProfileArn != "" {
updated.Metadata["profile_arn"] = tokenData.ProfileArn
}
if tokenData.AuthMethod != "" {
updated.Metadata["auth_method"] = tokenData.AuthMethod
}
if tokenData.Provider != "" {
updated.Metadata["provider"] = tokenData.Provider
}
// Preserve client credentials for future refreshes (AWS Builder ID)
if tokenData.ClientID != "" {
updated.Metadata["client_id"] = tokenData.ClientID
}
if tokenData.ClientSecret != "" {
updated.Metadata["client_secret"] = tokenData.ClientSecret
}
if updated.Attributes == nil {
updated.Attributes = make(map[string]string)
}
updated.Attributes["access_token"] = tokenData.AccessToken
if tokenData.ProfileArn != "" {
updated.Attributes["profile_arn"] = tokenData.ProfileArn
}
// NextRefreshAfter is aligned with RefreshLead (5min)
if expiresAt, parseErr := time.Parse(time.RFC3339, tokenData.ExpiresAt); parseErr == nil {
updated.NextRefreshAfter = expiresAt.Add(-5 * time.Minute)
}
log.Infof("kiro executor: token refreshed successfully, expires at %s", tokenData.ExpiresAt)
return updated, nil
}
// persistRefreshedAuth persists a refreshed auth record to disk.
// This ensures token refreshes from inline retry are saved to the auth file.
func (e *KiroExecutor) persistRefreshedAuth(auth *cliproxyauth.Auth) error {
if auth == nil || auth.Metadata == nil {
return fmt.Errorf("kiro executor: cannot persist nil auth or metadata")
}
// Determine the file path from auth attributes or filename
var authPath string
if auth.Attributes != nil {
if p := strings.TrimSpace(auth.Attributes["path"]); p != "" {
authPath = p
}
}
if authPath == "" {
fileName := strings.TrimSpace(auth.FileName)
if fileName == "" {
return fmt.Errorf("kiro executor: auth has no file path or filename")
}
if filepath.IsAbs(fileName) {
authPath = fileName
} else if e.cfg != nil && e.cfg.AuthDir != "" {
authPath = filepath.Join(e.cfg.AuthDir, fileName)
} else {
return fmt.Errorf("kiro executor: cannot determine auth file path")
}
}
// Marshal metadata to JSON
raw, err := json.Marshal(auth.Metadata)
if err != nil {
return fmt.Errorf("kiro executor: marshal metadata failed: %w", err)
}
// Write to temp file first, then rename (atomic write)
tmp := authPath + ".tmp"
if err := os.WriteFile(tmp, raw, 0o600); err != nil {
return fmt.Errorf("kiro executor: write temp auth file failed: %w", err)
}
if err := os.Rename(tmp, authPath); err != nil {
return fmt.Errorf("kiro executor: rename auth file failed: %w", err)
}
log.Debugf("kiro executor: persisted refreshed auth to %s", authPath)
return nil
}
// isTokenExpired checks if a JWT access token has expired.
// Returns true if the token is expired or cannot be parsed.
func (e *KiroExecutor) isTokenExpired(accessToken string) bool {
if accessToken == "" {
return true
}
// JWT tokens have 3 parts separated by dots
parts := strings.Split(accessToken, ".")
if len(parts) != 3 {
// Not a JWT token, assume not expired
return false
}
// Decode the payload (second part)
// JWT uses base64url encoding without padding (RawURLEncoding)
payload := parts[1]
decoded, err := base64.RawURLEncoding.DecodeString(payload)
if err != nil {
// Try with padding added as fallback
switch len(payload) % 4 {
case 2:
payload += "=="
case 3:
payload += "="
}
decoded, err = base64.URLEncoding.DecodeString(payload)
if err != nil {
log.Debugf("kiro: failed to decode JWT payload: %v", err)
return false
}
}
var claims struct {
Exp int64 `json:"exp"`
}
if err := json.Unmarshal(decoded, &claims); err != nil {
log.Debugf("kiro: failed to parse JWT claims: %v", err)
return false
}
if claims.Exp == 0 {
// No expiration claim, assume not expired
return false
}
expTime := time.Unix(claims.Exp, 0)
now := time.Now()
// Consider token expired if it expires within 1 minute (buffer for clock skew)
isExpired := now.After(expTime) || expTime.Sub(now) < time.Minute
if isExpired {
log.Debugf("kiro: token expired at %s (now: %s)", expTime.Format(time.RFC3339), now.Format(time.RFC3339))
}
return isExpired
}
// NOTE: Message merging functions moved to internal/translator/kiro/common/message_merge.go
// NOTE: Tool calling support functions moved to internal/translator/kiro/claude/kiro_claude_tools.go
// The executor now uses kiroclaude.* and kirocommon.* functions instead
|