Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 3x 3x 3x 3x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 1x 1x 7x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const { Meilisearch } = require('meilisearch');
const mongoose = require('mongoose');
const { v4: uuidv4 } = require('uuid');
const jwt = require('jsonwebtoken');
const axios = require('axios');
const Ajv = require('ajv');
const addFormats = require('ajv-formats');
const { validateBody, getUserId } = require('../shared/validation/src');
const { checkOrgAccess } = require('../shared/validation/src/org-auth');
const { kbSchemas } = require('./schemas');
const {
mergeThreshold,
mergeModel,
mergeRecords,
planMerge,
searchNearDuplicate,
fetchExistingVectors,
} = require('./merge');
dotenv.config();
const app = express();
const PORT = process.env.PORT || 8000;
const KNOWLEDGE_BASE_URL = process.env.KNOWLEDGE_BASE_URL || 'http://knowledge-base-service:8000';
const MEILISEARCH_URL = process.env.MEILISEARCH_URL || 'http://meilisearch:7700';
const MEILISEARCH_API_KEY = process.env.MEILISEARCH_MASTER_KEY;
const MONGODB_URI = process.env.MONGODB_URI || process.env.MONGODB_URL || 'mongodb://localhost:27017/nooloom';
const { signedAxios, CONFIG_SERVICE_URL } = require('../shared/signedAxios');
const { requireInternalKey } = require('../shared/internalAuth');
const { computeHash, buildKey, getFromCache, setToCache } = require('../shared/cache');
const EMBEDDING_MODEL = 'qwen/qwen3-embedding-8b';
// En recherche (hybride/vecteur), Meilisearch renvoie tout le corpus classé sans "total"
// exploitable → on scanne une fenêtre bornée depuis 0, on filtre par seuil, puis on pagine.
const SEARCH_SCAN_LIMIT = 200;
const OPENROUTER_BASE_URL = 'https://openrouter.ai/api/v1';
// Timeout et retries des appels d'embedding OpenRouter.
// Le suffixe `:nitro` (routage « fournisseur le plus rapide ») est retiré du modèle :
// il provoquait des pics de latence > 30 s sur certaines entrées, d'où des timeouts
// d'embedding puis des boucles d'agent RAG (GraphRecursionError). Le modèle
// sous-jacent est identique (4096 dimensions), aucun réindex n'est donc nécessaire.
const EMBEDDING_TIMEOUT_MS = 60000;
const EMBEDDING_MAX_RETRIES = 2;
const EMBEDDING_RETRY_BASE_DELAY_MS = 1000;
function normalizeEmbeddingModel(model) {
return (model || EMBEDDING_MODEL).replace(/:nitro$/, '');
}
async function requestEmbeddings(apiKey, model, input) {
let lastError;
for (let attempt = 0; attempt <= EMBEDDING_MAX_RETRIES; attempt++) {
try {
return await axios.post(
`${OPENROUTER_BASE_URL}/embeddings`,
{ model: normalizeEmbeddingModel(model), input, provider: { sort: 'latency' } },
{
headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
timeout: EMBEDDING_TIMEOUT_MS
}
);
} catch (e) {
lastError = e;
const status = e.response?.status;
const retriable = e.code === 'ECONNABORTED' || e.code === 'ETIMEDOUT' || !e.response || status === 429 || status >= 500;
if (!retriable || attempt === EMBEDDING_MAX_RETRIES) break;
const delay = EMBEDDING_RETRY_BASE_DELAY_MS * (2 ** attempt);
console.warn(`[Embedding] Tentative ${attempt + 1} échouée (${e.message}) — nouvel essai dans ${delay}ms`);
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
throw lastError;
}
// AJV validator for data KB documents (schema cached per KB)
const ajv = new Ajv({ allErrors: true, strict: false });
addFormats(ajv);
const documentValidatorCache = new Map();
function getDocumentValidator(kbId, schema) {
if (!schema) return null;
if (!documentValidatorCache.has(kbId)) {
try {
documentValidatorCache.set(kbId, ajv.compile(schema));
} catch (e) {
console.warn(`[KB Service] Invalid schema for KB ${kbId}: ${e.message}`);
documentValidatorCache.set(kbId, null);
}
}
return documentValidatorCache.get(kbId);
}
let meilisearchClient;
try {
meilisearchClient = new Meilisearch({
host: MEILISEARCH_URL,
apiKey: MEILISEARCH_API_KEY
});
console.log(`✅ Connected to Meilisearch at ${MEILISEARCH_URL}`);
} catch (e) {
console.log(`⚠️ Could not connect to Meilisearch: ${e.message}`);
meilisearchClient = null;
}
// ============================================================================
// Fusion d'entités à l'injection (cf. spec/prd-fusion-entites-kb.md)
// ============================================================================
/** Payload fusionnable d'un record : `data` (KB data) ou { text, source, url, confidence } (assertion). */
function mergePayloadOf(kb, record) {
if (kb.type === 'data') return record.data || {};
return {
text: record.text,
source: record.source || '',
url: record.url || null,
confidence: record.confidence ?? null,
};
}
/** Construit le record Meilisearch fusionné (id existant réutilisé, vecteurs cumulés). */
function buildMergedRecord(kb, hit, mergedPayload, vectors, incoming) {
const base = {
id: hit.id,
// `timestamp` = date de DERNIÈRE MISE À JOUR : rafraîchie à chaque fusion.
timestamp: new Date().toISOString(),
source: hit.source || incoming.source || '',
url: hit.url || incoming.url || null,
confidence: incoming.confidence ?? hit.confidence ?? 0.8,
_vectors: { openrouter: vectors },
};
if (kb.type === 'data') {
return { ...incoming, ...base, data: mergedPayload, text: JSON.stringify(mergedPayload) };
}
return {
...incoming,
...base,
text: String(mergedPayload.text || hit.text || incoming.text || ''),
source: mergedPayload.source || base.source,
url: mergedPayload.url || base.url,
confidence: mergedPayload.confidence ?? base.confidence,
};
}
/** Valide le payload fusionné (schéma AJV pour `data`, `text` non vide pour `assertion`). */
function isValidMergedPayload(kb, merged) {
if (kb.type === 'data') {
const validate = getDocumentValidator(String(kb._id), kb.schema);
return !validate || validate(merged);
}
return typeof merged.text === 'string' && merged.text.trim().length > 0;
}
/** Vecteur simple (number[]) d'un record, ou null. */
function singleVector(record) {
const v = record && record._vectors ? record._vectors.openrouter : null;
return Array.isArray(v) && v.length && typeof v[0] === 'number' ? v : null;
}
/**
* Indexe des records en tentant une fusion avec un éventuel doublon vectoriel.
* Traitement séquentiel ; tout échec → indexation brute (mode dégradé, jamais bloquant).
* @returns {Promise<{indexed:number, merged:number}>}
*/
async function indexWithMerge(kb, records, { openrouterApiKey } = {}) {
if (!meilisearchClient) {
return { indexed: 0, merged: 0 };
}
// Fusion désactivée sur cette KB → chaque nouvelle assertion/data devient sa propre entité
// (aucune recherche vectorielle ni fusion LLM).
if (kb.mergeOnIngest === false) {
for (const record of records) {
await meilisearchClient.index(kb.meilisearchId).addDocuments([record]);
}
return { indexed: records.length, merged: 0 };
}
const threshold = mergeThreshold();
const model = mergeModel();
let mergedCount = 0;
for (const record of records) {
let finalRecord = record;
try {
const vector = singleVector(record);
if (vector) {
const near = await searchNearDuplicate({
baseUrl: MEILISEARCH_URL,
apiKey: MEILISEARCH_API_KEY,
indexName: kb.meilisearchId,
vector,
threshold,
});
if (near && openrouterApiKey) {
const payloadA = mergePayloadOf(kb, near.hit);
const payloadB = mergePayloadOf(kb, record);
const res = await mergeRecords(payloadA, payloadB, { apiKey: openrouterApiKey, model });
if (res && isValidMergedPayload(kb, res.merged)) {
let existingVectors = [];
try {
existingVectors = await fetchExistingVectors({
baseUrl: MEILISEARCH_URL,
apiKey: MEILISEARCH_API_KEY,
indexName: kb.meilisearchId,
id: near.hit.id,
});
} catch (e) {
console.warn('[KB merge] vecteurs existants indisponibles:', e.message);
}
const { vectors } = planMerge({ id: near.hit.id, score: near.score, existingVectors, newVector: vector, threshold });
finalRecord = buildMergedRecord(kb, near.hit, res.merged, vectors, record);
mergedCount += 1;
if (res.cost > 0 && kb.organizationId) {
signedAxios.post(`${CONFIG_SERVICE_URL}/internal/usage/track`, { organizationId: kb.organizationId.toString(), llmCost: res.cost }, { timeout: 3000 }).catch(() => {});
}
console.log(`[KB merge] id=${finalRecord.id} score=${Number(near.score).toFixed(4)} vectors=${vectors.length} kb=${kb._id}`);
}
}
}
} catch (e) {
console.warn('[KB merge] échec, indexation brute:', e.message);
finalRecord = record;
}
await meilisearchClient.index(kb.meilisearchId).addDocuments([finalRecord]);
}
return { indexed: records.length, merged: mergedCount };
}
async function configureEmbedder(indexName) {
if (!meilisearchClient) return { success: false, error: 'Meilisearch not configured' };
try {
await meilisearchClient.index(indexName).updateSettings({
embedders: { openrouter: { source: 'userProvided', dimensions: 4096 } }
});
return { success: true };
} catch (e) {
return { success: false, error: e.message };
}
}
async function checkEmbedderConfig(indexName) {
if (!meilisearchClient) return { configured: false, error: 'Meilisearch not available' };
try {
const settings = await meilisearchClient.index(indexName).getSettings();
if (settings.embedders?.openrouter) {
return { configured: true };
}
return { configured: false, error: 'Embedder "openrouter" non configuré. Reconfigurez depuis les paramètres.' };
} catch (e) {
return { configured: false, error: e.message };
}
}
function buildHybridConfig(search_type, semantic_ratio) {
if (search_type === 'semantic' || search_type === 'hybrid') {
return {
semanticRatio: semantic_ratio !== undefined ? semantic_ratio : (search_type === 'semantic' ? 1.0 : 0.5),
embedder: 'openrouter'
};
}
return null;
}
const apiKeyCache = {};
async function getOpenRouterApiKey(authToken, organizationId) {
if (!organizationId) {
return null;
}
if (apiKeyCache[organizationId]) {
return apiKeyCache[organizationId];
}
try {
let response;
if (authToken) {
response = await axios.get(
`${CONFIG_SERVICE_URL}/${organizationId}/config/openrouter`,
{
headers: { 'Authorization': `Bearer ${authToken}` },
timeout: 5000
}
);
} else {
response = await signedAxios.get(
`${CONFIG_SERVICE_URL}/internal/${organizationId}/config/openrouter`,
{ timeout: 5000 }
);
}
if (response.data?.success) {
apiKeyCache[organizationId] = response.data.data.value;
return apiKeyCache[organizationId];
}
} catch (e) {
console.warn('[KnowledgeBase] Could not fetch OpenRouter API key:', e.message);
}
return null;
}
// Cache des embeddings : clé = hash(text) + hash(model) (tailles fixes, sha256)
const EMBEDDING_CACHE_TTL = 30 * 24 * 3600; // 30 jours
function embeddingCacheKey(text, model) {
return buildKey('embedding', computeHash(text), computeHash(model || ''));
}
async function readCachedEmbedding(text, model) {
const cached = await getFromCache(embeddingCacheKey(text, model));
if (!cached) return null;
try {
const vector = JSON.parse(cached);
return Array.isArray(vector) && vector.length > 0 ? vector : null;
} catch {
return null;
}
}
async function getEmbedding(query, apiKey, model) {
if (!apiKey) throw new Error('OpenRouter API key not available');
const normalizedModel = normalizeEmbeddingModel(model);
const cached = await readCachedEmbedding(query, normalizedModel);
if (cached) return { vector: cached, cost: 0, cached: true };
const response = await requestEmbeddings(apiKey, normalizedModel, query);
if (response.data?.data?.[0]?.embedding) {
const cost = response.data?.usage?.cost ? Math.round(response.data.usage.cost * 1000000) : 0;
const vector = response.data.data[0].embedding;
await setToCache(embeddingCacheKey(query, normalizedModel), JSON.stringify(vector), EMBEDDING_CACHE_TTL);
return { vector, cost };
}
throw new Error('Invalid embedding response');
}
async function getEmbeddingsBatch(texts, apiKey, model) {
if (!apiKey || !texts.length) throw new Error('OpenRouter API key not available');
const normalizedModel = normalizeEmbeddingModel(model);
// 1) Récupérer ce qui est déjà en cache
const vectors = new Array(texts.length);
const missingIdx = [];
const missingTexts = [];
for (let i = 0; i < texts.length; i++) {
const cached = await readCachedEmbedding(texts[i], normalizedModel);
if (cached) vectors[i] = cached;
else {
missingIdx.push(i);
missingTexts.push(texts[i]);
}
}
// 2) Appeler l'API uniquement pour les textes manquants
let cost = 0;
if (missingTexts.length > 0) {
const response = await requestEmbeddings(apiKey, normalizedModel, missingTexts);
const newVectors = response.data?.data?.map(d => d.embedding).filter(Boolean) || [];
if (newVectors.length !== missingTexts.length) {
throw new Error('Invalid batch embedding response');
}
cost = response.data?.usage?.cost ? Math.round(response.data.usage.cost * 1000000) : 0;
await Promise.all(missingIdx.map((idx, k) => {
vectors[idx] = newVectors[k];
return setToCache(embeddingCacheKey(texts[idx], normalizedModel), JSON.stringify(newVectors[k]), EMBEDDING_CACHE_TTL);
}));
}
return { vectors, cost, cached: missingTexts.length === 0 };
}
mongoose.connect(MONGODB_URI)
.then(() => console.log('✅ Connected to MongoDB'))
.catch(err => console.error('❌ MongoDB connection error:', err));
app.use(cors());
app.use(express.json());
const knowledgeBaseSchema = new mongoose.Schema({
meilisearchId: { type: String, required: true, unique: true },
organizationId: { type: String, required: true, index: true },
userId: { type: String, required: true, index: true },
name: { type: String, required: true },
description: { type: String, default: '' },
type: { type: String, enum: ['assertion', 'data'], default: 'assertion', index: true },
defaultPrompt: { type: String, default: '' },
schema: { type: mongoose.Schema.Types.Mixed, default: null },
searchableFields: { type: [String], default: ['*'] },
// Fusion d'entités à l'injection : `false` = chaque nouvelle assertion/data devient sa propre
// entité (aucune recherche/fusion) ; `true` (défaut) = rapprochement vectoriel + fusion LLM.
mergeOnIngest: { type: Boolean, default: true },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now },
embeddingModel: { type: String, default: 'qwen/qwen3-embedding-8b' }
});
knowledgeBaseSchema.index({ organizationId: 1, createdAt: -1 });
const KnowledgeBase = mongoose.model('KnowledgeBase', knowledgeBaseSchema);
// ============================================================================
// Virtual KB Model - Aggrégation virtuelle de plusieurs KBs réelles
// ============================================================================
const virtualKbSchema = new mongoose.Schema({
name: { type: String, required: true },
description: { type: String, default: '' },
organizationId: { type: String, required: true, index: true },
userId: { type: String, default: null },
kbIds: [{ type: mongoose.Schema.Types.ObjectId, ref: 'KnowledgeBase' }],
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});
virtualKbSchema.index({ organizationId: 1, createdAt: -1 });
const VirtualKB = mongoose.model('VirtualKB', virtualKbSchema);
// ============================================================================
// External API Config Model - Destinations de type "api" (niveau KB)
// ============================================================================
const externalApiConfigSchema = new mongoose.Schema({
organizationId: { type: String, required: true, index: true },
userId: { type: String, required: true, index: true },
name: { type: String, required: true, trim: true },
description: { type: String, default: '', trim: true },
url: {
type: String,
required: true,
trim: true,
validate: {
validator: v => /^https?:\/\//.test(v),
message: 'URL must start with http:// or https://'
}
},
isActive: { type: Boolean, default: true },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});
externalApiConfigSchema.index({ organizationId: 1, isActive: 1, createdAt: -1 });
const ExternalApiConfig = mongoose.model('ExternalApiConfig', externalApiConfigSchema);
function formatKbResponse(kb) {
const obj = kb.toObject ? kb.toObject() : { ...kb };
delete obj.__v;
return obj;
}
function formatKbListResponse(kbs) {
return kbs.map(formatKbResponse);
}
// ============================================================================
// Authentication Middleware (vérifie la signature JWT — défense en profondeur)
// ============================================================================
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({
success: false,
message: 'Access token required'
});
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
if (!decoded || !decoded.userId) {
return res.status(403).json({
success: false,
message: 'Invalid token'
});
}
req.user = { _id: decoded.userId, email: decoded.email, role: decoded.role };
next();
} catch (error) {
if (error.name === 'TokenExpiredError') {
return res.status(401).json({ success: false, message: 'Token expired' });
}
return res.status(403).json({
success: false,
message: 'Invalid token'
});
}
};
// ============================================================================
// ============================================================================
// Health Check
// ============================================================================
app.get('/health', async (req, res) => {
const services = { knowledge_base: 'up' };
if (meilisearchClient) {
try {
await meilisearchClient.health();
services.meilisearch = 'up';
} catch (e) {
services.meilisearch = 'down';
}
} else {
services.meilisearch = 'not_configured';
}
res.json({
status: 'healthy',
version: '1.0.0',
services
});
});
// ============================================================================
// Knowledge Base Management
// ============================================================================
app.post('/knowledge-bases/reindex-all', authenticateToken, async (req, res) => {
try {
const { organizationId } = req.body;
if (!organizationId) {
return res.status(400).json({ success: false, message: 'organizationId is required' });
}
if (!await checkOrgAccess(organizationId, req)) {
return res.status(403).json({ message: 'Access denied' });
}
if (!meilisearchClient) {
return res.status(503).json({ message: 'Meilisearch not available' });
}
const authToken = req.headers['authorization']?.split(' ')[1];
const openrouterApiKey = await getOpenRouterApiKey(authToken, organizationId);
if (!openrouterApiKey) {
return res.status(400).json({
success: false,
message: 'Clé API OpenRouter introuvable. Configurez-la dans Système → Configuration.'
});
}
const kbs = await KnowledgeBase.find({ organizationId });
const results = [];
for (const kb of kbs) {
try {
const allDocs = await meilisearchClient.index(kb.meilisearchId).getDocuments({ limit: 10000 });
const docs = allDocs.results || [];
if (docs.length > 0) {
// Ré-indexation NON destructive : les documents déjà porteurs de vecteurs (dont les
// records fusionnés multi-vecteurs) sont conservés tels quels ; seuls ceux dépourvus
// de vecteur sont ré-embarqués depuis `text`.
const missing = docs.filter(d => !d._vectors || !d._vectors.openrouter);
let batchCost = 0;
if (missing.length > 0) {
const texts = missing.map(d => d.text);
const emb = await getEmbeddingsBatch(texts, openrouterApiKey, kb.embeddingModel || EMBEDDING_MODEL);
batchCost = emb.cost;
missing.forEach((d, i) => { d._vectors = { openrouter: emb.vectors[i] }; });
}
await meilisearchClient.index(kb.meilisearchId).addDocuments(docs);
await kb.updateOne({ embeddingModel: normalizeEmbeddingModel(kb.embeddingModel) });
if (batchCost > 0 && kb.organizationId) {
signedAxios.post(`${CONFIG_SERVICE_URL}/internal/usage/track`, { organizationId: kb.organizationId.toString(), llmCost: batchCost }, { timeout: 3000 }).catch(() => {});
}
}
await configureEmbedder(kb.meilisearchId);
results.push({
kbId: kb._id.toString(),
name: kb.name,
success: true,
documentsReindexed: docs.length,
error: null
});
} catch (e) {
results.push({
kbId: kb._id.toString(),
name: kb.name,
success: false,
documentsReindexed: 0,
error: e.message
});
}
}
const successCount = results.filter(r => r.success).length;
res.json({
success: true,
message: `${successCount}/${kbs.length} KBs réindexées`,
data: { results }
});
} catch (error) {
console.error('Error reconfiguring all embedders:', error);
res.status(500).json({ message: 'Failed', error: error.message });
}
});
app.post('/knowledge-bases', authenticateToken, validateBody(kbSchemas.create), async (req, res) => {
try {
const { name, description, settings, organizationId, type, defaultPrompt, schema, searchableFields, mergeOnIngest } = req.body;
if (!organizationId) {
return res.status(400).json({
success: false,
message: 'organizationId is required'
});
}
const kbType = type === 'data' ? 'data' : 'assertion';
if (kbType === 'data' && !schema) {
return res.status(400).json({
success: false,
message: 'schema is required for data knowledge bases'
});
}
const meilisearchId = uuidv4();
const userId = req.user._id;
if (meilisearchClient && settings?.indexOnCreate !== false) {
try {
await meilisearchClient.createIndex(meilisearchId, { primaryKey: 'id' });
if (kbType === 'data') {
const searchableAttributes = (searchableFields && !searchableFields.includes('*'))
? searchableFields.map(f => f.startsWith('data.') ? f : `data.${f}`)
: ['*'];
const filterableAttributes = ['source', 'timestamp', 'confidence', 'url'];
await meilisearchClient.index(meilisearchId).updateSearchableAttributes(searchableAttributes);
await meilisearchClient.index(meilisearchId).updateFilterableAttributes(filterableAttributes);
await meilisearchClient.index(meilisearchId).updateSortableAttributes(['timestamp']);
} else {
const searchableAttributes = settings?.searchableAttributes || ['text'];
const filterableAttributes = settings?.filterableAttributes || ['source', 'timestamp', 'confidence'];
await meilisearchClient.index(meilisearchId).updateSearchableAttributes(searchableAttributes);
await meilisearchClient.index(meilisearchId).updateFilterableAttributes(filterableAttributes);
await meilisearchClient.index(meilisearchId).updateSortableAttributes(['timestamp']);
}
const authToken = req.headers['authorization']?.split(' ')[1];
const openrouterApiKey = await getOpenRouterApiKey(authToken, organizationId);
if (openrouterApiKey) {
await configureEmbedder(meilisearchId);
}
} catch (e) {
console.log('Index creation warning:', e.message);
}
}
const kb = new KnowledgeBase({
meilisearchId,
organizationId,
userId,
name,
description,
type: kbType,
defaultPrompt: kbType === 'assertion' ? (defaultPrompt || '') : '',
schema: kbType === 'data' ? schema : null,
searchableFields: kbType === 'data'
? (searchableFields && searchableFields.length > 0 ? searchableFields : ['*'])
: ['*'],
mergeOnIngest: typeof mergeOnIngest === 'boolean' ? mergeOnIngest : true
});
await kb.save();
res.status(201).json({
success: true,
message: 'Knowledge base created',
data: { knowledge_base: formatKbResponse(kb) }
});
} catch (error) {
console.error('Error creating knowledge base:', error);
res.status(500).json({
success: false,
message: 'Failed to create knowledge base',
error: error.message
});
}
});
app.post('/knowledge-bases/names', async (req, res) => {
try {
const { kbIds } = req.body;
console.log(`[KB Service] /knowledge-bases/names called with:`, kbIds);
if (!kbIds || !Array.isArray(kbIds)) {
return res.status(400).json({ success: false, message: 'kbIds array required' });
}
const kbs = await KnowledgeBase.find({ _id: { $in: kbIds } });
console.log(`[KB Service] Found ${kbs.length} KBs in MongoDB:`, kbs.map(kb => ({ id: kb._id, name: kb.name })));
const result = kbs.map(kb => ({ id: kb._id.toString(), name: kb.name }));
res.json({ success: true, data: result });
} catch (error) {
console.error('Error fetching KB names:', error);
res.status(500).json({ success: false, message: 'Internal error' });
}
});
app.get('/:organizationId/knowledge-bases', async (req, res) => {
try {
const { organizationId } = req.params;
const kbs = await KnowledgeBase.find({ organizationId }).sort({ createdAt: -1 });
const kbsWithStats = await Promise.all(
kbs.map(async (kb) => {
let meilisearchCount = 0;
if (meilisearchClient) {
try {
const stats = await meilisearchClient.index(kb.meilisearchId).getStats();
meilisearchCount = stats.numberOfDocuments || 0;
} catch (e) {
console.log('Stats warning for', kb.meilisearchId, e.message);
}
}
const obj = formatKbResponse(kb);
return {
...obj,
assertion_count: meilisearchCount,
fact_count: meilisearchCount
};
})
);
res.json({
success: true,
data: { knowledge_bases: kbsWithStats }
});
} catch (error) {
res.status(500).json({
success: false,
message: 'Failed to fetch knowledge bases',
error: error.message
});
}
});
/**
* Internal route (HMAC protected): item count for an organization.
* Used by config-service for usage/limits without walking the full KB list.
* Returns { organizationId, kbItemCount, knowledgeBases: [{ _id, name, assertion_count, fact_count }] }.
*/
app.get('/internal/:organizationId/knowledge-bases/count', requireInternalKey, async (req, res) => {
try {
const { organizationId } = req.params;
const kbs = await KnowledgeBase.find({ organizationId }).sort({ createdAt: -1 });
let kbItemCount = 0;
const knowledgeBases = await Promise.all(
kbs.map(async (kb) => {
let meilisearchCount = 0;
if (meilisearchClient) {
try {
const stats = await meilisearchClient.index(kb.meilisearchId).getStats();
meilisearchCount = stats.numberOfDocuments || 0;
} catch (e) {
console.log('Stats warning for', kb.meilisearchId, e.message);
}
}
kbItemCount += meilisearchCount;
return {
_id: kb._id.toString(),
name: kb.name,
assertion_count: meilisearchCount,
fact_count: meilisearchCount,
};
})
);
res.json({
success: true,
data: { organizationId, kbItemCount, knowledgeBases },
});
} catch (error) {
res.status(500).json({
success: false,
message: 'Failed to count knowledge base items',
error: error.message,
});
}
});
app.get('/knowledge-bases/:id', async (req, res) => {
try {
const kb = await KnowledgeBase.findOne({ _id: req.params.id });
if (!kb) {
return res.status(404).json({
success: false,
message: 'Knowledge base not found'
});
}
if (!await checkOrgAccess(kb.organizationId, req)) {
return res.status(403).json({ message: 'Access denied to this resource' });
}
res.json({
success: true,
data: { knowledge_base: formatKbResponse(kb) }
});
} catch (error) {
res.status(500).json({
success: false,
message: 'Failed to fetch knowledge base',
error: error.message
});
}
});
async function applyKbUpdate(req, res, method) {
try {
const existingKb = await KnowledgeBase.findOne({ _id: req.params.id });
if (!existingKb) {
return res.status(404).json({
success: false,
message: 'Knowledge base not found'
});
}
if (!await checkOrgAccess(existingKb.organizationId, req)) {
return res.status(403).json({ message: 'Access denied to this resource' });
}
if (req.body.type && req.body.type !== existingKb.type) {
return res.status(400).json({ success: false, message: 'Type cannot be changed after creation' });
}
const updates = { ...req.body, updatedAt: new Date() };
delete updates.type;
if (existingKb.type === 'assertion') {
delete updates.schema;
delete updates.searchableFields;
} else {
delete updates.defaultPrompt;
}
const kb = await KnowledgeBase.findOneAndUpdate(
{ _id: req.params.id },
updates,
{ new: true }
);
// Re-synchroniser les searchableAttributes si schema/searchableFields changent (type data)
let warning = null;
if (kb.type === 'data' && meilisearchClient &&
(req.body.schema !== undefined || req.body.searchableFields !== undefined)) {
try {
const fields = kb.searchableFields && kb.searchableFields.length > 0
? kb.searchableFields
: ['*'];
const searchableAttributes = fields.includes('*')
? ['*']
: fields.map(f => f.startsWith('data.') ? f : `data.${f}`);
await meilisearchClient.index(kb.meilisearchId).updateSearchableAttributes(searchableAttributes);
await meilisearchClient.index(kb.meilisearchId).updateSortableAttributes(['timestamp']);
const stats = await meilisearchClient.index(kb.meilisearchId).getStats().catch(() => null);
if (stats && stats.numberOfDocuments > 0) {
warning = 'Schema modified: existing documents were not re-validated. Re-import or re-index them to ensure consistency.';
}
documentValidatorCache.delete(String(kb._id));
} catch (e) {
console.warn(`[KB Service] Failed to update searchable attributes: ${e.message}`);
}
}
res.json({
success: true,
message: 'Knowledge base updated',
data: { knowledge_base: formatKbResponse(kb) },
...(warning ? { warning } : {})
});
} catch (error) {
console.error(`Error updating knowledge base (${method}):`, error);
res.status(500).json({
success: false,
message: 'Failed to update knowledge base',
error: error.message
});
}
}
app.put('/knowledge-bases/:id', validateBody(kbSchemas.update), async (req, res) => {
return applyKbUpdate(req, res, 'PUT');
});
app.patch('/knowledge-bases/:id', validateBody(kbSchemas.update), async (req, res) => {
return applyKbUpdate(req, res, 'PATCH');
});
// Vide le CONTENU d'une KB (assertions / documents) sans supprimer la base.
app.delete('/knowledge-bases/:id/documents', async (req, res) => {
try {
const kb = await KnowledgeBase.findById(req.params.id);
if (!kb) {
return res.status(404).json({ success: false, message: 'Knowledge base not found' });
}
if (!await checkOrgAccess(kb.organizationId, req)) {
return res.status(403).json({ success: false, message: 'Access denied to this resource' });
}
if (meilisearchClient) {
try {
await meilisearchClient.index(kb.meilisearchId).deleteAllDocuments();
} catch (e) {
console.log('Empty warning:', e.message);
}
}
res.json({ success: true, message: 'Knowledge base emptied' });
} catch (error) {
res.status(500).json({ success: false, message: 'Failed to empty knowledge base', error: error.message });
}
});
app.delete('/knowledge-bases/:id', async (req, res) => {
try {
const kb = await KnowledgeBase.findOne({ _id: req.params.id });
if (!kb) {
return res.status(404).json({
success: false,
message: 'Knowledge base not found'
});
}
if (!await checkOrgAccess(kb.organizationId, req)) {
return res.status(403).json({ message: 'Access denied to this resource' });
}
const meilisearchIndexId = kb.meilisearchId;
await KnowledgeBase.findOneAndDelete({ _id: req.params.id });
if (meilisearchClient) {
try {
await meilisearchClient.deleteIndex(meilisearchIndexId);
} catch (e) {
console.log('Index deletion warning:', e.message);
}
}
const db = mongoose.connection.db;
const kbIdStr = String(req.params.id);
// Cascade : retirer la KB des agents
try {
const r = await db.collection('agents').updateMany(
{ knowledgeBaseIds: kbIdStr },
{ $pull: { knowledgeBaseIds: kbIdStr } }
);
if (r.modifiedCount > 0) console.log(`[Cascade] Nettoyé ${r.modifiedCount} agent(s) référençant KB ${kbIdStr}`);
} catch (e) { console.warn('[Cascade] agents:', e.message); }
// Cascade : retirer la KB des workflows
try {
const r = await db.collection('workflows').updateMany(
{ targetKnowledgeBases: kbIdStr },
{ $pull: { targetKnowledgeBases: kbIdStr } }
);
if (r.modifiedCount > 0) console.log(`[Cascade] Nettoyé ${r.modifiedCount} workflow(s) référençant KB ${kbIdStr}`);
} catch (e) { console.warn('[Cascade] workflows:', e.message); }
// Cascade : retirer la KB des bases virtuelles
try {
const r = await db.collection('virtualkbs').updateMany(
{ kbIds: kbIdStr },
{ $pull: { kbIds: kbIdStr } }
);
if (r.modifiedCount > 0) console.log(`[Cascade] Nettoyé ${r.modifiedCount} base(s) virtuelle(s) référençant KB ${kbIdStr}`);
} catch (e) { console.warn('[Cascade] virtualkbs:', e.message); }
// Cascade : retirer la KB des workflows (destinations)
try {
const r = await db.collection('workflows').updateMany(
{ 'destinations.id': kbIdStr },
{ $pull: { destinations: { id: kbIdStr } } }
);
if (r.modifiedCount > 0) console.log(`[Cascade] Nettoyé ${r.modifiedCount} workflow(s) référençant KB ${kbIdStr}`);
} catch (e) { console.warn('[Cascade] workflows destinations:', e.message); }
// Cascade : retirer la KB des crawlers (config.destinations)
try {
const r = await db.collection('crawlerconfigs').updateMany(
{ 'config.destinations.id': kbIdStr },
{ $pull: { 'config.destinations': { id: kbIdStr } } }
);
if (r.modifiedCount > 0) console.log(`[Cascade] Nettoyé ${r.modifiedCount} crawler(s) référençant KB ${kbIdStr}`);
} catch (e) { console.warn('[Cascade] crawlerconfigs destinations:', e.message); }
res.json({
success: true,
message: 'Knowledge base deleted'
});
} catch (error) {
res.status(500).json({
success: false,
message: 'Failed to delete knowledge base',
error: error.message
});
}
});
// ============================================================================
// Assertions Management
// ============================================================================
async function createAssertion(req, res) {
try {
const kb = await KnowledgeBase.findOne({ _id: req.params.kbId });
if (!kb) {
return res.status(404).json({
success: false,
message: 'Knowledge base not found'
});
}
if (kb.type === 'data') {
return res.status(400).json({
success: false,
message: 'This knowledge base is of type "data". Use POST /knowledge-bases/:kbId/documents instead.'
});
}
// Vérifier la limite KB avant d'ajouter une assertion
try {
const configCheck = await signedAxios.post(`${CONFIG_SERVICE_URL}/internal/usage/check-kb`, {
organizationId: kb.organizationId.toString(),
count: 1,
}, { timeout: 5000 });
const checkData = configCheck.data?.data || configCheck.data;
if (!checkData?.allowed) {
return res.status(429).json({ success: false, message: 'KB item limit exceeded. Please upgrade your plan or delete existing items.' });
}
} catch (checkErr) {
if (checkErr.response?.status === 429) {
return res.status(429).json({ success: false, message: 'KB item limit exceeded. Please upgrade your plan or delete existing items.' });
}
}
const assertionText = typeof req.body === 'string' ? req.body : req.body.text || JSON.stringify(req.body);
if (meilisearchClient) {
try {
const assertionId = uuidv4();
const confidence = req.body.confidence || 0.8;
const assertionUrl = req.body.url || req.body.metadata?.url || null;
const doc = {
id: assertionId,
text: assertionText,
confidence: confidence,
source: req.body.source || '',
url: assertionUrl,
timestamp: new Date().toISOString()
};
const authToken = req.headers['authorization']?.split(' ')[1];
const openrouterApiKey = await getOpenRouterApiKey(authToken, kb.organizationId);
if (openrouterApiKey) {
const { vector, cost: embCost } = await getEmbedding(assertionText, openrouterApiKey, kb.embeddingModel || EMBEDDING_MODEL);
doc._vectors = { openrouter: vector };
await kb.updateOne({ embeddingModel: normalizeEmbeddingModel(kb.embeddingModel) });
// Tracker le coût de l'embedding
if (embCost > 0 && kb.organizationId) {
signedAxios.post(`${CONFIG_SERVICE_URL}/internal/usage/track`, { organizationId: kb.organizationId.toString(), llmCost: embCost }, { timeout: 3000 }).catch(() => {});
}
}
await indexWithMerge(kb, [doc], { openrouterApiKey });
return res.status(201).json({
success: true,
message: 'Assertion created',
data: {
assertion: {
id: assertionId,
text: assertionText,
confidence: confidence,
source: req.body.source || ''
}
}
});
} catch (e) {
console.log('Meilisearch indexing warning:', e.message);
return res.status(500).json({
success: false,
message: 'Failed to index assertion',
error: e.message
});
}
}
return res.status(503).json({
success: false,
message: 'Meilisearch not available'
});
} catch (error) {
console.error('Error creating assertion:', error);
res.status(500).json({
success: false,
message: 'Failed to create assertion',
error: error.message
});
}
}
async function createAssertionsBatch(req, res) {
try {
const kb = await KnowledgeBase.findOne({ _id: req.params.kbId });
if (!kb) {
return res.status(404).json({
success: false,
message: 'Knowledge base not found'
});
}
if (kb.type === 'data') {
return res.status(400).json({
success: false,
message: 'This knowledge base is of type "data". Use POST /knowledge-bases/:kbId/documents instead.'
});
}
// Vérifier la limite KB avant d'ajouter des assertions en batch
try {
const count = (req.body.facts || req.body.assertions || []).length;
const configCheck = await signedAxios.post(`${CONFIG_SERVICE_URL}/internal/usage/check-kb`, {
organizationId: kb.organizationId.toString(),
count,
}, { timeout: 5000 });
const checkData = configCheck.data?.data || configCheck.data;
if (!checkData?.allowed) {
return res.status(429).json({ success: false, message: 'KB item limit exceeded. Please upgrade your plan or delete existing items.' });
}
} catch (checkErr) {
if (checkErr.response?.status === 429) {
return res.status(429).json({ success: false, message: 'KB item limit exceeded. Please upgrade your plan or delete existing items.' });
}
}
if (!meilisearchClient) {
return res.status(503).json({
success: false,
message: 'Meilisearch not available'
});
}
const items = req.body.facts || req.body.assertions || [];
const assertions = items.map(f => {
const assertionText = typeof f === 'string' ? f : f.text || JSON.stringify(f);
const assertionUrl = typeof f === 'string' ? null : (f.url || f.metadata?.url || null);
return {
// Id stable fourni par le dispatch (idempotence des rejeux) ; repli uuid
// pour les appels directs (UI, MCP) qui n'en fournissent pas.
id: f.id || uuidv4(),
text: assertionText,
confidence: f.confidence || 0.5,
source: typeof f.source === 'string' ? f.source : '',
url: assertionUrl,
timestamp: new Date().toISOString()
};
});
const authToken = req.headers['authorization']?.split(' ')[1];
const openrouterApiKey = await getOpenRouterApiKey(authToken, kb.organizationId);
if (openrouterApiKey && assertions.length > 0) {
const texts = assertions.map(f => f.text);
const { vectors, cost: batchCost } = await getEmbeddingsBatch(texts, openrouterApiKey, kb.embeddingModel || EMBEDDING_MODEL);
for (let i = 0; i < assertions.length; i++) {
assertions[i]._vectors = { openrouter: vectors[i] };
}
await kb.updateOne({ embeddingModel: normalizeEmbeddingModel(kb.embeddingModel)});
// Tracker le coût des embeddings batch
if (batchCost > 0 && kb.organizationId) {
signedAxios.post(`${CONFIG_SERVICE_URL}/internal/usage/track`, { organizationId: kb.organizationId.toString(), llmCost: batchCost }, { timeout: 3000 }).catch(() => {});
}
}
try {
await indexWithMerge(kb, assertions, { openrouterApiKey });
} catch (e) {
console.log('Meilisearch batch indexing error:', e.message);
return res.status(500).json({
success: false,
message: 'Failed to index assertions',
error: e.message
});
}
res.status(201).json({
success: true,
message: `${assertions.length} assertions indexed`,
data: { count: assertions.length }
});
} catch (error) {
console.error('Error creating assertions batch:', error);
res.status(500).json({
success: false,
message: 'Failed to create assertions',
error: error.message
});
}
}
app.post('/knowledge-bases/:kbId/assertions', authenticateToken, validateBody(kbSchemas.createAssertion), createAssertion);
app.post('/knowledge-bases/:kbId/assertions/batch', authenticateToken, validateBody(kbSchemas.createAssertionsBatch), createAssertionsBatch);
// Legacy aliases (previously /facts)
app.post('/knowledge-bases/:kbId/facts', authenticateToken, validateBody(kbSchemas.createAssertion), createAssertion);
app.post('/knowledge-bases/:kbId/facts/batch', authenticateToken, validateBody(kbSchemas.createAssertionsBatch), createAssertionsBatch);
// ============================================================================
// Data Documents Management (KB type 'data')
// ============================================================================
async function createDocuments(req, res) {
try {
const kb = await KnowledgeBase.findOne({ _id: req.params.kbId });
if (!kb) {
return res.status(404).json({
success: false,
message: 'Knowledge base not found'
});
}
if (kb.type !== 'data') {
return res.status(400).json({
success: false,
message: 'This knowledge base is of type "assertion". Use POST /knowledge-bases/:kbId/assertions instead.'
});
}
if (!kb.schema) {
return res.status(400).json({
success: false,
message: 'This knowledge base has no JSON schema defined'
});
}
const items = Array.isArray(req.body) ? req.body : [req.body];
// Valider chaque document contre le schéma de la base
const validator = getDocumentValidator(String(kb._id), kb.schema);
if (!validator) {
return res.status(400).json({
success: false,
message: 'Invalid schema defined on this knowledge base'
});
}
const validationErrors = [];
for (let i = 0; i < items.length; i++) {
if (!validator(items[i].data)) {
validationErrors.push({ index: i, errors: validator.errors.map(e => ({
path: e.instancePath || '/',
message: e.message,
keyword: e.keyword
})) });
}
}
if (validationErrors.length > 0) {
return res.status(400).json({
success: false,
message: `Validation failed for ${validationErrors.length} document(s) against the knowledge base schema`,
errors: validationErrors
});
}
// Vérifier la limite KB avant d'ajouter des documents
try {
const configCheck = await signedAxios.post(`${CONFIG_SERVICE_URL}/internal/usage/check-kb`, {
organizationId: kb.organizationId.toString(),
count: items.length,
}, { timeout: 5000 });
const checkData = configCheck.data?.data || configCheck.data;
if (!checkData?.allowed) {
return res.status(429).json({ success: false, message: 'KB item limit exceeded. Please upgrade your plan or delete existing items.' });
}
} catch (checkErr) {
if (checkErr.response?.status === 429) {
return res.status(429).json({ success: false, message: 'KB item limit exceeded. Please upgrade your plan or delete existing items.' });
}
}
if (!meilisearchClient) {
return res.status(503).json({
success: false,
message: 'Meilisearch not available'
});
}
const documents = items.map(item => {
const doc = {
// Id stable si fourni (idempotence), sinon uuid.
id: item.id || uuidv4(),
data: item.data,
text: JSON.stringify(item.data),
source: typeof item.source === 'string' ? item.source : '',
url: item.url || null,
confidence: item.confidence ?? 0.8,
timestamp: new Date().toISOString()
};
return doc;
});
const authToken = req.headers['authorization']?.split(' ')[1];
const openrouterApiKey = await getOpenRouterApiKey(authToken, kb.organizationId);
if (openrouterApiKey && documents.length > 0) {
try {
const texts = documents.map(d => d.text);
const { vectors, cost: batchCost } = await getEmbeddingsBatch(texts, openrouterApiKey, kb.embeddingModel || EMBEDDING_MODEL);
for (let i = 0; i < documents.length; i++) {
documents[i]._vectors = { openrouter: vectors[i] };
}
await kb.updateOne({ embeddingModel: normalizeEmbeddingModel(kb.embeddingModel) });
if (batchCost > 0 && kb.organizationId) {
signedAxios.post(`${CONFIG_SERVICE_URL}/internal/usage/track`, { organizationId: kb.organizationId.toString(), llmCost: batchCost }, { timeout: 3000 }).catch(() => {});
}
} catch (e) {
console.warn('[KB Service] Embedding generation failed, indexing without vectors:', e.message);
}
}
try {
await indexWithMerge(kb, documents, { openrouterApiKey });
} catch (e) {
console.log('Meilisearch documents indexing error:', e.message);
return res.status(500).json({
success: false,
message: 'Failed to index documents',
error: e.message
});
}
res.status(201).json({
success: true,
message: `${documents.length} document(s) indexed`,
data: {
count: documents.length,
documents: documents.map(d => ({ id: d.id, data: d.data }))
}
});
} catch (error) {
console.error('Error creating documents:', error);
res.status(500).json({
success: false,
message: 'Failed to create documents',
error: error.message
});
}
}
app.post('/knowledge-bases/:kbId/documents', authenticateToken, validateBody(kbSchemas.createDocuments), createDocuments);
app.post('/knowledge-bases/:kbId/documents/batch', authenticateToken, validateBody(kbSchemas.createDocumentsBatch), createDocuments);
// ============================================================================
// Routes INTERNES HMAC (activités → KB) — cf. spec/prd-remove-xconfig-id.md
// Aucun credential utilisateur : HMAC (x-internal-token) + organisation explicite.
// Le contrôle d'accès est direct (kb.organizationId === organizationId), sans Redis.
// ============================================================================
async function internalKbOrgGuard(req, res, next) {
try {
const organizationId = req.query.organizationId || req.body?.organizationId;
if (!organizationId) {
return res.status(400).json({ success: false, message: 'organizationId is required' });
}
const kb = await KnowledgeBase.findOne({ _id: req.params.kbId }, { organizationId: 1 }).lean();
if (!kb) return res.status(404).json({ success: false, message: 'Knowledge base not found' });
if (String(kb.organizationId) !== String(organizationId)) {
return res.status(403).json({ success: false, message: 'Access denied to this organization' });
}
next();
} catch (error) {
res.status(500).json({ success: false, message: 'Internal org check failed', error: error.message });
}
}
app.post(
'/internal/knowledge-bases/:kbId/assertions/batch',
requireInternalKey,
internalKbOrgGuard,
validateBody(kbSchemas.createAssertionsBatch),
createAssertionsBatch
);
app.post(
'/internal/knowledge-bases/:kbId/documents/batch',
requireInternalKey,
internalKbOrgGuard,
validateBody(kbSchemas.createDocumentsBatch),
createDocuments
);
app.get('/internal/knowledge-bases/:kbId', requireInternalKey, internalKbOrgGuard, async (req, res) => {
try {
const kb = await KnowledgeBase.findById(req.params.kbId).lean();
if (!kb) return res.status(404).json({ success: false, message: 'Knowledge base not found' });
res.json({
success: true,
data: {
_id: kb._id,
name: kb.name,
type: kb.type,
defaultPrompt: kb.defaultPrompt || null,
schema: kb.schema || null,
embeddingModel: normalizeEmbeddingModel(kb.embeddingModel),
},
});
} catch (error) {
res.status(500).json({ success: false, message: 'Failed to resolve knowledge base', error: error.message });
}
});
app.get('/internal/external-apis/:apiId', requireInternalKey, async (req, res) => {
try {
const { organizationId } = req.query;
const api = await ExternalApiConfig.findOne({ _id: req.params.apiId, isActive: true });
if (!api) return res.status(404).json({ success: false, message: 'External API not found' });
if (!organizationId || String(api.organizationId) !== String(organizationId)) {
return res.status(403).json({ success: false, message: 'Access denied to this organization' });
}
res.json({ success: true, data: formatExternalApi(api) });
} catch (error) {
res.status(500).json({ success: false, message: 'Failed to resolve external API', error: error.message });
}
});
// ============================================================================
// Virtual KB - CRUD
// ============================================================================
app.get('/:organizationId/virtual-kbs', async (req, res) => {
try {
const vkbs = await VirtualKB.find({ organizationId: req.params.organizationId })
.populate('kbIds', 'name')
.sort({ createdAt: -1 });
res.json({ success: true, data: vkbs });
} catch (error) {
res.status(500).json({ success: false, message: 'Failed to list virtual KBs', error: error.message });
}
});
app.post('/:organizationId/virtual-kbs', async (req, res) => {
try {
const { name, description, kbIds } = req.body;
if (!name) return res.status(400).json({ success: false, message: 'Name is required' });
const vkb = await VirtualKB.create({
organizationId: req.params.organizationId,
name, description: description || '',
kbIds: kbIds || []
});
res.status(201).json({ success: true, data: vkb });
} catch (error) {
res.status(500).json({ success: false, message: 'Failed to create virtual KB', error: error.message });
}
});
app.get('/virtual-kbs/:id', async (req, res) => {
try {
const vkb = await VirtualKB.findById(req.params.id).populate('kbIds', 'name');
if (!vkb) return res.status(404).json({ success: false, message: 'Virtual KB not found' });
if (!await checkOrgAccess(vkb.organizationId, req)) {
return res.status(403).json({ message: 'Access denied' });
}
res.json({ success: true, data: vkb });
} catch (error) {
res.status(500).json({ success: false, message: 'Failed to fetch virtual KB', error: error.message });
}
});
app.put('/virtual-kbs/:id', async (req, res) => {
try {
const vkb = await VirtualKB.findById(req.params.id);
if (!vkb) return res.status(404).json({ success: false, message: 'Virtual KB not found' });
if (!await checkOrgAccess(vkb.organizationId, req)) {
return res.status(403).json({ message: 'Access denied' });
}
const { name, description, kbIds } = req.body;
if (name !== undefined) vkb.name = name;
if (description !== undefined) vkb.description = description;
if (kbIds !== undefined) vkb.kbIds = kbIds;
vkb.updatedAt = new Date();
await vkb.save();
res.json({ success: true, data: vkb });
} catch (error) {
res.status(500).json({ success: false, message: 'Failed to update virtual KB', error: error.message });
}
});
app.delete('/virtual-kbs/:id', async (req, res) => {
try {
const vkb = await VirtualKB.findById(req.params.id);
if (!vkb) return res.status(404).json({ success: false, message: 'Virtual KB not found' });
if (!await checkOrgAccess(vkb.organizationId, req)) {
return res.status(403).json({ message: 'Access denied' });
}
await VirtualKB.findByIdAndDelete(req.params.id);
res.json({ success: true, message: 'Virtual KB deleted' });
} catch (error) {
res.status(500).json({ success: false, message: 'Failed to delete virtual KB', error: error.message });
}
});
// Org-prefixed routes (called by gateway CRUD_RESOURCES: /api/v1/:orgId/virtual-kbs/:id)
app.get('/:organizationId/virtual-kbs/:id', async (req, res) => {
try {
const vkb = await VirtualKB.findById(req.params.id).populate('kbIds', 'name');
if (!vkb) return res.status(404).json({ success: false, message: 'Virtual KB not found' });
if (!await checkOrgAccess(vkb.organizationId, req))
return res.status(403).json({ message: 'Access denied' });
res.json({ success: true, data: vkb });
} catch (error) {
res.status(500).json({ success: false, message: 'Failed to fetch virtual KB', error: error.message });
}
});
app.put('/:organizationId/virtual-kbs/:id', async (req, res) => {
try {
const vkb = await VirtualKB.findById(req.params.id);
if (!vkb) return res.status(404).json({ success: false, message: 'Virtual KB not found' });
if (!await checkOrgAccess(vkb.organizationId, req))
return res.status(403).json({ message: 'Access denied' });
const { name, description, kbIds } = req.body;
if (name !== undefined) vkb.name = name;
if (description !== undefined) vkb.description = description;
if (kbIds !== undefined) vkb.kbIds = kbIds;
vkb.updatedAt = new Date();
await vkb.save();
res.json({ success: true, data: vkb });
} catch (error) {
res.status(500).json({ success: false, message: 'Failed to update virtual KB', error: error.message });
}
});
app.delete('/:organizationId/virtual-kbs/:id', async (req, res) => {
try {
const vkb = await VirtualKB.findById(req.params.id);
if (!vkb) return res.status(404).json({ success: false, message: 'Virtual KB not found' });
if (!await checkOrgAccess(vkb.organizationId, req))
return res.status(403).json({ message: 'Access denied' });
await VirtualKB.findByIdAndDelete(req.params.id);
res.json({ success: true, message: 'Virtual KB deleted' });
} catch (error) {
res.status(500).json({ success: false, message: 'Failed to delete virtual KB', error: error.message });
}
});
// ============================================================================
// External APIs CRUD - Destinations de type "api" (niveau KB)
// ============================================================================
function formatExternalApi(api) {
const obj = api.toObject ? api.toObject() : { ...api };
delete obj.__v;
return obj;
}
app.get('/:organizationId/external-apis', async (req, res) => {
try {
const apis = await ExternalApiConfig.find({
organizationId: req.params.organizationId,
isActive: true
}).sort({ createdAt: -1 });
res.json({ success: true, data: apis.map(formatExternalApi) });
} catch (error) {
res.status(500).json({ success: false, message: 'Failed to list external APIs', error: error.message });
}
});
app.post('/external-apis', authenticateToken, async (req, res) => {
try {
const { name, description, url, organizationId } = req.body;
if (!name) return res.status(400).json({ success: false, message: 'Name is required' });
if (!organizationId) return res.status(400).json({ success: false, message: 'organizationId is required' });
if (!url || !/^https?:\/\//.test(url)) {
return res.status(400).json({ success: false, message: 'A valid URL (http/https) is required' });
}
const userId = getUserId(req);
const api = await ExternalApiConfig.create({
organizationId,
userId: userId || null,
name,
description: description || '',
url
});
res.status(201).json({ success: true, message: 'External API created', data: formatExternalApi(api) });
} catch (error) {
res.status(500).json({ success: false, message: 'Failed to create external API', error: error.message });
}
});
app.get('/external-apis/:id', async (req, res) => {
try {
const api = await ExternalApiConfig.findOne({ _id: req.params.id, isActive: true });
if (!api) return res.status(404).json({ success: false, message: 'External API not found' });
if (!await checkOrgAccess(api.organizationId, req))
return res.status(403).json({ message: 'Access denied' });
res.json({ success: true, data: formatExternalApi(api) });
} catch (error) {
res.status(500).json({ success: false, message: 'Failed to fetch external API', error: error.message });
}
});
app.put('/external-apis/:id', async (req, res) => {
try {
const existing = await ExternalApiConfig.findOne({ _id: req.params.id, isActive: true });
if (!existing) return res.status(404).json({ success: false, message: 'External API not found' });
if (!await checkOrgAccess(existing.organizationId, req))
return res.status(403).json({ message: 'Access denied' });
const { name, description, url } = req.body;
const updates = { updatedAt: new Date() };
if (name !== undefined) updates.name = name;
if (description !== undefined) updates.description = description;
if (url !== undefined) {
if (!/^https?:\/\//.test(url)) {
return res.status(400).json({ success: false, message: 'A valid URL (http/https) is required' });
}
updates.url = url;
}
const api = await ExternalApiConfig.findOneAndUpdate(
{ _id: req.params.id, isActive: true },
updates,
{ new: true }
);
res.json({ success: true, message: 'External API updated', data: formatExternalApi(api) });
} catch (error) {
res.status(500).json({ success: false, message: 'Failed to update external API', error: error.message });
}
});
app.delete('/external-apis/:id', async (req, res) => {
try {
const existing = await ExternalApiConfig.findOne({ _id: req.params.id, isActive: true });
if (!existing) return res.status(404).json({ success: false, message: 'External API not found' });
if (!await checkOrgAccess(existing.organizationId, req))
return res.status(403).json({ message: 'Access denied' });
await ExternalApiConfig.findOneAndUpdate(
{ _id: req.params.id, isActive: true },
{ $set: { isActive: false, updatedAt: new Date() } }
);
res.json({ success: true, message: 'External API deleted' });
} catch (error) {
res.status(500).json({ success: false, message: 'Failed to delete external API', error: error.message });
}
});
// Org-prefixed aliases (appelés via gateway CRUD_RESOURCES : /api/v1/:orgId/external-apis/:id)
app.get('/:organizationId/external-apis/:id', async (req, res) => {
const api = await ExternalApiConfig.findOne({ _id: req.params.id, isActive: true });
if (!api) return res.status(404).json({ success: false, message: 'External API not found' });
if (!await checkOrgAccess(api.organizationId, req))
return res.status(403).json({ message: 'Access denied' });
res.json({ success: true, data: formatExternalApi(api) });
});
app.put('/:organizationId/external-apis/:id', async (req, res) => {
const existing = await ExternalApiConfig.findOne({ _id: req.params.id, isActive: true });
if (!existing) return res.status(404).json({ success: false, message: 'External API not found' });
if (!await checkOrgAccess(existing.organizationId, req))
return res.status(403).json({ message: 'Access denied' });
const { name, description, url } = req.body;
const updates = { updatedAt: new Date() };
if (name !== undefined) updates.name = name;
if (description !== undefined) updates.description = description;
if (url !== undefined) {
if (!/^https?:\/\//.test(url)) {
return res.status(400).json({ success: false, message: 'A valid URL (http/https) is required' });
}
updates.url = url;
}
const api = await ExternalApiConfig.findOneAndUpdate(
{ _id: req.params.id, isActive: true },
updates,
{ new: true }
);
res.json({ success: true, message: 'External API updated', data: formatExternalApi(api) });
});
app.delete('/:organizationId/external-apis/:id', async (req, res) => {
const existing = await ExternalApiConfig.findOne({ _id: req.params.id, isActive: true });
if (!existing) return res.status(404).json({ success: false, message: 'External API not found' });
if (!await checkOrgAccess(existing.organizationId, req))
return res.status(403).json({ message: 'Access denied' });
await ExternalApiConfig.findOneAndUpdate(
{ _id: req.params.id, isActive: true },
{ $set: { isActive: false, updatedAt: new Date() } }
);
res.json({ success: true, message: 'External API deleted' });
});
app.post('/:organizationId/virtual-kbs/:id/search/nooloom', async (req, res) => {
try {
const vkb = await VirtualKB.findById(req.params.id).populate('kbIds');
if (!vkb) return res.status(404).json({ success: false, message: 'Virtual KB not found' });
if (!await checkOrgAccess(vkb.organizationId, req))
return res.status(403).json({ message: 'Access denied' });
if (!meilisearchClient) return res.status(503).json({ message: 'Meilisearch not available' });
if (!vkb.kbIds.length) return res.json({ kbName: vkb.name, assertions: [], facts: [], total: 0 });
const body = req.body;
const query = body.q || body.search;
if (!query) return res.status(400).json({ message: 'No search query provided (use "q" field)' });
const limit = body.limit || 10;
const score_threshold = body.score_threshold;
const threshold = score_threshold !== undefined ? score_threshold : 0;
const hybridConfig = body.hybrid;
if (hybridConfig && !hybridConfig.embedder) hybridConfig.embedder = 'openrouter';
let vector = null;
if (hybridConfig) {
const authToken = req.headers['authorization']?.split(' ')[1];
const openrouterApiKey = await getOpenRouterApiKey(authToken, vkb.organizationId);
if (openrouterApiKey) {
try { const { vector: embVec, cost: embCost } = await getEmbedding(query, openrouterApiKey, EMBEDDING_MODEL); vector = embVec; if (embCost > 0 && vkb.organizationId) { signedAxios.post(`\${CONFIG_SERVICE_URL}/internal/usage/track`, { organizationId: vkb.organizationId.toString(), llmCost: embCost }, { timeout: 3000 }).catch(() => {}); } }
catch (e) { return res.status(502).json({ message: 'Embedding failed', error: e.message }); }
}
}
const perKb = Math.max(1, Math.ceil(limit / vkb.kbIds.length));
const searchParams = { limit: perKb, showRankingScore: true };
if (vector) { searchParams.vector = vector; searchParams.hybrid = hybridConfig; }
const allResults = await Promise.all(vkb.kbIds.map(kb =>
meilisearchClient.index(kb.meilisearchId).search(query, searchParams)
.then(r => ({ kbName: kb.name, hits: r.hits, total: r.estimatedTotalHits || 0 }))
.catch(() => ({ kbName: kb.name, hits: [], total: 0 }))
));
const merged = allResults.flatMap(r => r.hits.map(h => ({
id: h.id, text: h.text, score: h._rankingScore || 0,
source: h.source || '', url: h.url || null,
kbName: r.kbName, metadata: h.metadata || null, data: h.data || null, confidence: h.confidence || null, timestamp: h.timestamp
}))).filter(f => f.score >= threshold).sort((a, b) => (b.score || 0) - (a.score || 0)).slice(0, limit);
res.json({
data: {
kbName: vkb.name, assertions: merged, facts: merged, total: merged.length, limit,
sources: vkb.kbIds.map(kb => ({ name: kb.name, id: kb._id }))
}
});
} catch (error) {
res.status(500).json({ message: 'Virtual KB search failed', error: error.message });
}
});
app.post('/:organizationId/virtual-kbs/:id/search/meilisearch', async (req, res) => {
try {
const vkb = await VirtualKB.findById(req.params.id).populate('kbIds');
if (!vkb) return res.status(404).json({ message: 'Virtual KB not found' });
if (!await checkOrgAccess(vkb.organizationId, req))
return res.status(403).json({ message: 'Access denied' });
if (!meilisearchClient) return res.status(503).json({ message: 'Meilisearch not available' });
if (!vkb.kbIds.length) return res.json({ hits: [], estimatedTotalHits: 0 });
const body = req.body;
const query = body.q || body.search;
if (!query) return res.status(400).json({ message: 'No search query provided (use "q" field)' });
const limit = body.limit || 10;
const perKb = Math.max(1, Math.ceil(limit / vkb.kbIds.length));
const searchParams = { limit: perKb, offset: body.offset || 0, showRankingScore: true };
const rawHybrid = body.hybrid;
if (rawHybrid && !rawHybrid.embedder) rawHybrid.embedder = 'openrouter';
if (rawHybrid) {
const authToken = req.headers['authorization']?.split(' ')[1];
const openrouterApiKey = await getOpenRouterApiKey(authToken, vkb.organizationId);
if (openrouterApiKey) {
try {
const { vector, cost: embCost } = await getEmbedding(query, openrouterApiKey, EMBEDDING_MODEL);
searchParams.vector = vector;
if (embCost > 0 && vkb?.organizationId) { signedAxios.post(`${CONFIG_SERVICE_URL}/internal/usage/track`, { organizationId: vkb.organizationId.toString(), llmCost: embCost }, { timeout: 3000 }).catch(() => {}); }
searchParams.hybrid = rawHybrid;
} catch (e) {
console.error('[VirtualKB MeiliProxy] Embedding failed, falling back:', e.message);
searchParams.hybrid = rawHybrid;
}
} else {
searchParams.hybrid = rawHybrid;
}
}
const allResults = await Promise.all(vkb.kbIds.map(kb =>
meilisearchClient.index(kb.meilisearchId).search(query, searchParams)
.then(r => ({ kbName: kb.name, hits: r.hits, total: r.estimatedTotalHits || 0 }))
.catch(() => ({ kbName: kb.name, hits: [], total: 0 }))
));
const mergedHits = allResults.flatMap(r => r.hits.map(h => ({
...h, _kbName: r.kbName
}))).sort((a, b) => (b._rankingScore || 0) - (a._rankingScore || 0)).slice(0, limit);
res.json({
hits: mergedHits,
estimatedTotalHits: allResults.reduce((s, r) => s + r.total, 0),
query, limit, offset: body.offset || 0,
processingTimeMs: 0,
sources: vkb.kbIds.map(kb => ({ name: kb.name, id: kb._id }))
});
} catch (error) {
res.status(500).json({ message: 'Virtual KB Meilisearch search failed', error: error.message });
}
});
app.post('/virtual-kbs/:id/search/nooloom', async (req, res) => {
try {
const vkb = await VirtualKB.findById(req.params.id).populate('kbIds');
if (!vkb) return res.status(404).json({ success: false, message: 'Virtual KB not found' });
if (!await checkOrgAccess(vkb.organizationId, req))
return res.status(403).json({ message: 'Access denied' });
if (!meilisearchClient) return res.status(503).json({ message: 'Meilisearch not available' });
if (!vkb.kbIds.length) return res.json({ kbName: vkb.name, assertions: [], facts: [], total: 0 });
const body = req.body;
const query = body.q || body.search;
if (!query) return res.status(400).json({ message: 'No search query provided (use "q" field)' });
const limit = body.limit || 10;
const score_threshold = body.score_threshold;
const threshold = score_threshold !== undefined ? score_threshold : 0;
const hybridConfig = body.hybrid;
if (hybridConfig && !hybridConfig.embedder) hybridConfig.embedder = 'openrouter';
let vector = null;
if (hybridConfig) {
const authToken = req.headers['authorization']?.split(' ')[1];
const openrouterApiKey = await getOpenRouterApiKey(authToken, vkb.organizationId);
if (openrouterApiKey) {
try { const { vector: embVec, cost: embCost } = await getEmbedding(query, openrouterApiKey, EMBEDDING_MODEL); vector = embVec; if (embCost > 0 && vkb.organizationId) { signedAxios.post(`\${CONFIG_SERVICE_URL}/internal/usage/track`, { organizationId: vkb.organizationId.toString(), llmCost: embCost }, { timeout: 3000 }).catch(() => {}); } }
catch (e) { return res.status(502).json({ message: 'Embedding failed', error: e.message }); }
}
}
const perKb = Math.max(1, Math.ceil(limit / vkb.kbIds.length));
const searchParams = { limit: perKb, showRankingScore: true };
if (vector) { searchParams.vector = vector; searchParams.hybrid = hybridConfig; }
const allResults = await Promise.all(vkb.kbIds.map(kb =>
meilisearchClient.index(kb.meilisearchId).search(query, searchParams)
.then(r => ({ kbName: kb.name, hits: r.hits, total: r.estimatedTotalHits || 0 }))
.catch(() => ({ kbName: kb.name, hits: [], total: 0 }))
));
const merged = allResults.flatMap(r => r.hits.map(h => ({
id: h.id, text: h.text, score: h._rankingScore || 0,
source: h.source || '', url: h.url || null,
kbName: r.kbName, metadata: h.metadata || null, data: h.data || null, confidence: h.confidence || null, timestamp: h.timestamp
}))).filter(f => f.score >= threshold).sort((a, b) => (b.score || 0) - (a.score || 0)).slice(0, limit);
res.json({
data: {
kbName: vkb.name, assertions: merged, facts: merged, total: merged.length, limit,
sources: vkb.kbIds.map(kb => ({ name: kb.name, id: kb._id }))
}
});
} catch (error) {
res.status(500).json({ message: 'Virtual KB search failed', error: error.message });
}
});
app.post('/virtual-kbs/:id/search/meilisearch', async (req, res) => {
try {
const vkb = await VirtualKB.findById(req.params.id).populate('kbIds');
if (!vkb) return res.status(404).json({ message: 'Virtual KB not found' });
if (!await checkOrgAccess(vkb.organizationId, req))
return res.status(403).json({ message: 'Access denied' });
if (!meilisearchClient) return res.status(503).json({ message: 'Meilisearch not available' });
if (!vkb.kbIds.length) return res.json({ hits: [], estimatedTotalHits: 0 });
const body = req.body;
const query = body.q || body.search;
if (!query) return res.status(400).json({ message: 'No search query provided (use "q" field)' });
const limit = body.limit || 10;
const perKb = Math.max(1, Math.ceil(limit / vkb.kbIds.length));
const searchParams = { limit: perKb, offset: body.offset || 0, showRankingScore: true };
const rawHybrid = body.hybrid;
if (rawHybrid && !rawHybrid.embedder) rawHybrid.embedder = 'openrouter';
if (rawHybrid) {
const authToken = req.headers['authorization']?.split(' ')[1];
const openrouterApiKey = await getOpenRouterApiKey(authToken, vkb.organizationId);
if (openrouterApiKey) {
try {
const { vector, cost: embCost } = await getEmbedding(query, openrouterApiKey, EMBEDDING_MODEL);
searchParams.vector = vector;
if (embCost > 0 && vkb?.organizationId) { signedAxios.post(`${CONFIG_SERVICE_URL}/internal/usage/track`, { organizationId: vkb.organizationId.toString(), llmCost: embCost }, { timeout: 3000 }).catch(() => {}); }
searchParams.hybrid = rawHybrid;
} catch (e) {
console.error('[VirtualKB MeiliProxy] Embedding failed, falling back:', e.message);
searchParams.hybrid = rawHybrid;
}
} else {
searchParams.hybrid = rawHybrid;
}
}
const allResults = await Promise.all(vkb.kbIds.map(kb =>
meilisearchClient.index(kb.meilisearchId).search(query, searchParams)
.then(r => ({ kbName: kb.name, hits: r.hits, total: r.estimatedTotalHits || 0 }))
.catch(() => ({ kbName: kb.name, hits: [], total: 0 }))
));
const mergedHits = allResults.flatMap(r => r.hits.map(h => ({
...h, _kbName: r.kbName
}))).sort((a, b) => (b._rankingScore || 0) - (a._rankingScore || 0)).slice(0, limit);
res.json({
hits: mergedHits,
estimatedTotalHits: allResults.reduce((s, r) => s + r.total, 0),
query, limit, offset: body.offset || 0,
processingTimeMs: 0,
sources: vkb.kbIds.map(kb => ({ name: kb.name, id: kb._id }))
});
} catch (error) {
res.status(500).json({ message: 'Virtual KB Meilisearch search failed', error: error.message });
}
});
app.get('/:organizationId/virtual-kbs/:id/api-info', async (req, res) => {
try {
const vkb = await VirtualKB.findById(req.params.id).populate('kbIds', 'name');
if (!vkb) return res.status(404).json({ success: false, message: 'Virtual KB not found' });
if (!await checkOrgAccess(vkb.organizationId, req))
return res.status(403).json({ message: 'Access denied' });
const apiUrl = process.env.API_PUBLIC_URL || 'http://localhost:8000';
const sources = vkb.kbIds.map(kb => ({ id: kb._id, name: kb.name }));
res.json({
name: vkb.name, sources,
meilisearch: {
url: `${apiUrl}/api/v1/virtual-kbs/${vkb._id}/search/meilisearch`,
searchUrl: `${apiUrl}/api/v1/virtual-kbs/${vkb._id}/search/meilisearch`,
curlExample: `curl -X POST '${apiUrl}/api/v1/virtual-kbs/${vkb._id}/search/meilisearch' \\\n -H 'x-api-key: <VOTRE_CLE_API>' \\\n -H 'Content-Type: application/json' \\\n -d '{"q": "votre requete", "limit": 5, "hybrid": {"semanticRatio": 0.5}}'`
},
nooloomSearch: {
url: `${apiUrl}/api/v1/virtual-kbs/${vkb._id}/search/nooloom`,
method: 'POST',
headers: { 'x-api-key': '<VOTRE_CLE_API>', 'Content-Type': 'application/json' },
body: { q: 'votre requete', limit: 5, hybrid: { semanticRatio: 0.5 } },
curlExample: `curl -X POST '${apiUrl}/api/v1/virtual-kbs/${vkb._id}/search/nooloom' \\\n -H 'x-api-key: <VOTRE_CLE_API>' \\\n -H 'Content-Type: application/json' \\\n -d '{"q": "votre requete", "limit": 5, "hybrid": {"semanticRatio": 0.5}}'`
}
});
} catch (error) {
res.status(500).json({ message: 'Failed to get API info', error: error.message });
}
});
app.get('/virtual-kbs/:id/api-info', async (req, res) => {
try {
const vkb = await VirtualKB.findById(req.params.id).populate('kbIds', 'name');
if (!vkb) return res.status(404).json({ success: false, message: 'Virtual KB not found' });
if (!await checkOrgAccess(vkb.organizationId, req)) {
return res.status(403).json({ message: 'Access denied' });
}
const apiUrl = process.env.API_PUBLIC_URL || 'http://localhost:8000';
const sources = vkb.kbIds.map(kb => ({ id: kb._id, name: kb.name }));
res.json({
name: vkb.name, sources,
meilisearch: {
url: `${apiUrl}/api/v1/virtual-kbs/${vkb._id}/search/meilisearch`,
searchUrl: `${apiUrl}/api/v1/virtual-kbs/${vkb._id}/search/meilisearch`,
curlExample: `curl -X POST '${apiUrl}/api/v1/virtual-kbs/${vkb._id}/search/meilisearch' \\\n -H 'x-api-key: <VOTRE_CLE_API>' \\\n -H 'Content-Type: application/json' \\\n -d '{"q": "votre requete", "limit": 5, "hybrid": {"semanticRatio": 0.5}}'`
},
nooloomSearch: {
url: `${apiUrl}/api/v1/virtual-kbs/${vkb._id}/search/nooloom`,
method: 'POST',
headers: { 'x-api-key': '<VOTRE_CLE_API>', 'Content-Type': 'application/json' },
body: { q: 'votre requete', limit: 5, hybrid: { semanticRatio: 0.5 } },
curlExample: `curl -X POST '${apiUrl}/api/v1/virtual-kbs/${vkb._id}/search/nooloom' \\\n -H 'x-api-key: <VOTRE_CLE_API>' \\\n -H 'Content-Type: application/json' \\\n -d '{"q": "votre requete", "limit": 5, "hybrid": {"semanticRatio": 0.5}}'`
}
});
} catch (error) {
res.status(500).json({ message: 'Failed to get API info', error: error.message });
}
});
// ============================================================================
// Search
// ============================================================================
app.post('/knowledge-bases/:kbId/search/nooloom', async (req, res) => {
try {
const kb = await KnowledgeBase.findOne({ _id: req.params.kbId });
if (!kb) {
return res.status(404).json({
success: false,
message: 'Knowledge base not found'
});
}
if (!await checkOrgAccess(kb.organizationId, req)) {
return res.status(403).json({ message: 'Access denied to this resource' });
}
if (!meilisearchClient) {
return res.status(503).json({
success: false,
message: 'Meilisearch not available'
});
}
const body = req.body;
// q vide = lister toutes les assertions (pagination)
const query = body.q ?? '';
const hasQuery = typeof query === 'string' && query.trim().length > 0;
const limit = body.limit || 10;
const offset = body.offset || 0;
const score_threshold = body.score_threshold;
const hybridConfig = body.hybrid;
if (hybridConfig && !hybridConfig.embedder) {
hybridConfig.embedder = 'openrouter';
}
const isList = !hasQuery;
const searchParams = {
// Recherche : on scanne une fenêtre bornée depuis 0 (puis pagination côté service).
// Liste : pagination déléguée à Meilisearch (offset exact).
limit: isList ? limit : SEARCH_SCAN_LIMIT,
offset: isList ? offset : 0,
showRankingScore: true,
};
let meiliFilter = body.filter;
if (body.filters?.min_confidence !== undefined) {
const confidenceFilter = `confidence >= ${body.filters.min_confidence}`;
meiliFilter = meiliFilter ? `${meiliFilter} AND ${confidenceFilter}` : confidenceFilter;
}
if (meiliFilter) {
searchParams.filter = meiliFilter;
}
// Mode "lister tout" : du plus récent au plus ancien
if (!hasQuery) {
searchParams.sort = ['timestamp:desc'];
}
console.log(`[Search] Body reçu:`, JSON.stringify({ query, limit, hybrid: hybridConfig }));
const reqStart = Date.now();
if (hybridConfig && hasQuery) {
const authToken = req.headers['authorization']?.split(' ')[1];
const openrouterApiKey = await getOpenRouterApiKey(authToken, kb.organizationId);
if (openrouterApiKey) {
try {
const { vector, cost: embCost } = await getEmbedding(query, openrouterApiKey, kb.embeddingModel || EMBEDDING_MODEL);
searchParams.vector = vector;
if (embCost > 0 && kb.organizationId) {
signedAxios.post(`${CONFIG_SERVICE_URL}/internal/usage/track`, { organizationId: kb.organizationId.toString(), llmCost: embCost }, { timeout: 3000 }).catch(() => {});
}
searchParams.hybrid = hybridConfig;
console.log(`[Search] Embedding récupéré (${vector.length} dims), ratio=${hybridConfig.semanticRatio}, embedTime=${Date.now() - reqStart}ms`);
} catch (e) {
console.error(`[Search] Échec embedding:`, e.message);
return res.status(502).json({ success: false, message: 'Recherche vectorielle impossible', error: `Service d\'embedding indisponible: ${e.message}` });
}
} else {
const isPureVector = hybridConfig.semanticRatio >= 1;
if (isPureVector) {
return res.status(400).json({ success: false, message: 'Recherche vectorielle impossible', warning: 'Clé API OpenRouter introuvable' });
}
}
}
console.log(`[Search] Paramètres Meilisearch:`, JSON.stringify({ ...searchParams, vector: searchParams.vector ? `[${searchParams.vector.length} dims]` : undefined }));
const startTime = Date.now();
let results;
try {
results = await meilisearchClient.index(kb.meilisearchId).search(query, searchParams);
} catch (e) {
// Index pas encore configuré avec `timestamp` triable → repli sans tri
if (!hasQuery && searchParams.sort) {
console.warn(`[Search] Tri "timestamp" indisponible, repli sans tri: ${e.message}`);
delete searchParams.sort;
results = await meilisearchClient.index(kb.meilisearchId).search(query, searchParams);
} else {
throw e;
}
}
const totalTime = Date.now() - reqStart;
console.log(`[Search] Retour: ${results.hits.length} hits, total=${results.estimatedTotalHits}, totalTime=${totalTime}ms, meiliTime=${results.processingTimeMs}ms`);
const assertions = results.hits.map(hit => ({
id: hit.id,
text: hit.text,
score: hit._rankingScore,
source: hit.source || '',
url: hit.url || hit.source || null,
metadata: hit.metadata || null,
data: hit.data || null,
confidence: hit.confidence || null,
timestamp: hit.timestamp,
}));
// Le seuil ne s'applique qu'en recherche (pas en mode "lister tout")
const threshold = (hasQuery && score_threshold !== undefined) ? score_threshold : 0;
const filteredAssertions = threshold > 0
? assertions.filter(f => (f.score ?? 0) >= threshold)
: assertions;
// Mode liste : estimatedTotalHits exact → pagination directe.
// Recherche : on pagine sur la fenêtre scannée (total fiable, borné par SEARCH_SCAN_LIMIT).
let pageItems;
let total;
if (isList) {
pageItems = filteredAssertions;
total = results.estimatedTotalHits ?? filteredAssertions.length;
} else {
total = filteredAssertions.length;
pageItems = filteredAssertions.slice(offset, offset + limit);
}
const data = {
kbId: kb.meilisearchId,
kbName: kb.name,
assertions: pageItems,
facts: pageItems,
total,
hasMore: offset + limit < total,
limit: limit,
offset: isList ? results.offset : offset,
search_type: isList ? 'list' : 'hybrid',
processing_time_ms: results.processingTimeMs
};
res.json(data);
} catch (error) {
console.error('Search error:', error);
res.status(500).json({
success: false,
message: 'Search failed',
error: error.message
});
}
});
app.post('/search', authenticateToken, validateBody(kbSchemas.globalSearch), async (req, res) => {
try {
const { organizationId, query, search_type, knowledgeBaseIds, limit, semantic_ratio } = req.body;
if (!organizationId) {
return res.status(400).json({
success: false,
message: 'organizationId is required'
});
}
const kbs = knowledgeBaseIds
? await KnowledgeBase.find({ id: { $in: knowledgeBaseIds }, organizationId })
: await KnowledgeBase.find({ organizationId });
if (!meilisearchClient || kbs.length === 0) {
return res.json({
success: true,
data: { results: [] }
});
}
const searchParams = {
limit: limit || 5,
showRankingScore: true
};
const hybrid = buildHybridConfig(search_type, semantic_ratio);
if (hybrid) {
searchParams.hybrid = hybrid;
}
const allResults = [];
for (const kb of kbs) {
try {
const results = await meilisearchClient.index(kb.meilisearchId).search(query, searchParams);
allResults.push({
knowledgeBaseId: kb.meilisearchId,
knowledgeBaseName: kb.name,
assertions: results.hits.map(hit => ({
id: hit.id,
text: hit.text,
score: hit._rankingScore,
source: hit.source || '',
url: hit.url || hit.source || null,
metadata: hit.metadata || null,
data: hit.data || null,
confidence: hit.confidence || null,
timestamp: hit.timestamp,
})),
facts: results.hits.map(hit => ({
id: hit.id,
text: hit.text,
score: hit._rankingScore,
source: hit.source || '',
url: hit.url || hit.source || null,
metadata: hit.metadata || null,
data: hit.data || null,
confidence: hit.confidence || null,
timestamp: hit.timestamp,
}))
});
} catch (e) {
console.log(`Search warning for ${kb.meilisearchId}:`, e.message);
}
}
res.json({
success: true,
data: {
results: allResults,
search_type: search_type || 'fulltext'
}
});
} catch (error) {
console.error('Global search error:', error);
res.status(500).json({
success: false,
message: 'Global search failed',
error: error.message
});
}
});
app.get('/knowledge-bases/:kbId/api-info', async (req, res) => {
try {
const kb = await KnowledgeBase.findOne({ _id: req.params.kbId });
if (!kb) {
return res.status(404).json({ message: 'Knowledge base not found' });
}
if (!await checkOrgAccess(kb.organizationId, req)) {
return res.status(403).json({ message: 'Access denied to this resource' });
}
const apiUrl = process.env.API_PUBLIC_URL || 'http://localhost:8000';
const meilisearchInfo = {
url: `${apiUrl}/api/v1/knowledge-bases/${kb._id}/search/meilisearch`,
apiKey: MEILISEARCH_API_KEY,
indexName: kb.meilisearchId,
searchUrl: `${apiUrl}/api/v1/knowledge-bases/${kb._id}/search/meilisearch`,
curlExample: `curl -X POST '${apiUrl}/api/v1/knowledge-bases/${kb._id}/search/meilisearch' \\\n -H 'x-api-key: <VOTRE_CLE_API>' \\\n -H 'Content-Type: application/json' \\\n -d '{"q": "votre requete", "limit": 5, "hybrid": {"semanticRatio": 0.5}}'`
};
const nooloomSearchInfo = {
url: `${apiUrl}/api/v1/knowledge-bases/${kb._id}/search/nooloom`,
method: 'POST',
headers: {
'x-api-key': '<VOTRE_CLE_API>',
'Content-Type': 'application/json'
},
body: {
q: 'votre requete',
limit: 5,
hybrid: { semanticRatio: 0.5 }
},
curlExample: `curl -X POST '${apiUrl}/api/v1/knowledge-bases/${kb._id}/search/nooloom' \\\n -H 'x-api-key: <VOTRE_CLE_API>' \\\n -H 'Content-Type: application/json' \\\n -d '{"q": "votre requete", "limit": 5, "hybrid": {"semanticRatio": 0.5}}'`
};
res.json({
knowledgeBase: { id: kb._id, name: kb.name, organizationId: kb.organizationId },
meilisearch: meilisearchInfo,
nooloomSearch: nooloomSearchInfo
});
} catch (error) {
console.error('API info error:', error);
res.status(500).json({ success: false, message: 'Failed to fetch API info', error: error.message });
}
});
// ============================================================================
// Raw Meilisearch Proxy - Pass-through to Meilisearch API
// ============================================================================
app.post('/knowledge-bases/:kbId/search/meilisearch', async (req, res) => {
try {
const kb = await KnowledgeBase.findOne({ _id: req.params.kbId });
if (!kb) {
return res.status(404).json({ message: 'Knowledge base not found' });
}
if (!await checkOrgAccess(kb.organizationId, req)) {
return res.status(403).json({ message: 'Access denied to this resource' });
}
if (!meilisearchClient) {
return res.status(503).json({ message: 'Meilisearch not available' });
}
const body = req.body;
const meiliIndex = meilisearchClient.index(kb.meilisearchId);
const query = body.q;
if (!query) {
return res.status(400).json({ message: 'No search query provided (use "q" field)' });
}
const searchParams = { limit: body.limit || 10, offset: body.offset || 0, showRankingScore: true };
const rawHybrid = body.hybrid;
if (rawHybrid && !rawHybrid.embedder) {
rawHybrid.embedder = 'openrouter';
}
if (rawHybrid) {
const authToken = req.headers['authorization']?.split(' ')[1];
const openrouterApiKey = await getOpenRouterApiKey(authToken, kb.organizationId);
if (openrouterApiKey) {
try {
const { vector, cost: embCost } = await getEmbedding(query, openrouterApiKey, kb.embeddingModel || EMBEDDING_MODEL);
searchParams.vector = vector;
if (embCost > 0 && kb.organizationId) {
signedAxios.post(`${CONFIG_SERVICE_URL}/internal/usage/track`, { organizationId: kb.organizationId.toString(), llmCost: embCost }, { timeout: 3000 }).catch(() => {});
}
searchParams.hybrid = rawHybrid;
} catch (e) {
console.error('[MeiliProxy] Embedding failed, falling back to REST embedder:', e.message);
searchParams.hybrid = rawHybrid;
}
} else {
searchParams.hybrid = rawHybrid;
}
}
const results = await meiliIndex.search(query, searchParams);
res.json(results);
} catch (error) {
console.error('Meilisearch proxy error:', error);
res.status(500).json({ message: 'Meilisearch proxy failed', error: error.message });
}
});
// ============================================================================
// Stats
// ============================================================================
app.get('/knowledge-bases/:kbId/config', async (req, res) => {
try {
const kb = await KnowledgeBase.findOne({ _id: req.params.kbId });
if (!kb) {
return res.status(404).json({
success: false,
message: 'Knowledge base not found'
});
}
if (!await checkOrgAccess(kb.organizationId, req)) {
return res.status(403).json({ message: 'Access denied to this resource' });
}
if (!meilisearchClient) {
return res.status(503).json({
success: false,
message: 'Meilisearch not available'
});
}
const rawParams = { ...req.body };
const results = await meilisearchClient.index(kb.meilisearchId).search(
rawParams.q || rawParams.query || '',
rawParams
);
res.json(results);
} catch (error) {
console.error('Meilisearch proxy error:', error);
res.status(500).json({
success: false,
message: 'Meilisearch proxy failed',
error: error.message
});
}
});
app.get('/knowledge-bases/:kbId/stats', async (req, res) => {
try {
const kb = await KnowledgeBase.findOne({ _id: req.params.kbId });
if (!kb) {
return res.status(404).json({
success: false,
message: 'Knowledge base not found'
});
}
if (!await checkOrgAccess(kb.organizationId, req)) {
return res.status(403).json({ message: 'Access denied to this resource' });
}
let meilisearchStats = null;
let indexConfig = null;
let embedderConfig = null;
if (meilisearchClient) {
try {
meilisearchStats = await meilisearchClient.index(kb.meilisearchId).getStats();
} catch (e) {
console.log('Stats warning:', e.message);
}
try {
const settings = await meilisearchClient.index(kb.meilisearchId).getSettings();
indexConfig = {
searchableAttributes: settings.searchableAttributes || ['text'],
filterableAttributes: settings.filterableAttributes || ['source', 'timestamp', 'confidence']
};
if (settings.embedders && settings.embedders.openrouter) {
embedderConfig = {
provider: 'openrouter',
model: settings.embedders.openrouter.request?.model || EMBEDDING_MODEL,
documentTemplate: settings.embedders.openrouter.documentTemplate || '{{text}}',
isConfigured: true
};
} else {
embedderConfig = {
provider: 'openrouter',
model: null,
documentTemplate: '{{text}}',
isConfigured: false
};
}
} catch (e) {
console.log('Settings warning:', e.message);
indexConfig = {
searchableAttributes: ['text'],
filterableAttributes: ['source', 'timestamp', 'confidence']
};
embedderConfig = {
provider: 'openrouter',
model: null,
documentTemplate: '{{text}}',
isConfigured: false
};
}
} else {
indexConfig = {
searchableAttributes: ['text'],
filterableAttributes: ['source', 'timestamp', 'confidence']
};
embedderConfig = {
provider: 'openrouter',
model: null,
documentTemplate: '{{text}}',
isConfigured: false
};
}
res.json({
success: true,
data: {
knowledge_base: {
id: kb.meilisearchId,
name: kb.name,
meilisearchStats
},
index_config: indexConfig,
embedder: embedderConfig
}
});
} catch (error) {
res.status(500).json({
success: false,
message: 'Failed to fetch stats',
error: error.message
});
}
});
app.post('/knowledge-bases/:kbId/reindex', async (req, res) => {
try {
const { kbId } = req.params;
const kb = await KnowledgeBase.findOne({ _id: kbId });
if (!kb) return res.status(404).json({ message: 'Knowledge base not found' });
if (!await checkOrgAccess(kb.organizationId, req))
return res.status(403).json({ message: 'Access denied to this resource' });
const authToken = req.headers['authorization']?.split(' ')[1];
const openrouterApiKey = await getOpenRouterApiKey(authToken, kb.organizationId);
if (!openrouterApiKey) return res.status(400).json({ success: false, message: 'OpenRouter API key not available' });
const allDocs = await meilisearchClient.index(kb.meilisearchId).getDocuments({ limit: 10000 });
if (!allDocs.results?.length) {
await configureEmbedder(kb.meilisearchId);
return res.json({ message: 'No documents to reindex, embedder configured', documentsCount: 0 });
}
const results = allDocs.results;
// Préserve les vecteurs existants (records fusionnés multi-vecteurs) ; n'embarque que les manquants.
const missing = results.filter(d => !d._vectors || !d._vectors.openrouter);
let reindexCost = 0;
if (missing.length > 0) {
const texts = missing.map(d => (d.data ? JSON.stringify(d.data) : d.text));
const emb = await getEmbeddingsBatch(texts, openrouterApiKey, kb.embeddingModel || EMBEDDING_MODEL);
reindexCost = emb.cost;
missing.forEach((d, i) => { d._vectors = { openrouter: emb.vectors[i] }; });
}
// Tracker le coût des embeddings de réindexation
if (reindexCost > 0 && kb.organizationId) {
signedAxios.post(`${CONFIG_SERVICE_URL}/internal/usage/track`, { organizationId: kb.organizationId.toString(), llmCost: reindexCost }, { timeout: 3000 }).catch(() => {});
}
const docsWithId = results.map((doc) => ({
...doc,
text: doc.text || JSON.stringify(doc.data || {}),
}));
await meilisearchClient.index(kb.meilisearchId).addDocuments(docsWithId);
await kb.updateOne({ embeddingModel: normalizeEmbeddingModel(kb.embeddingModel) });
await configureEmbedder(kb.meilisearchId);
res.json({ message: `Reindexed ${docsWithId.length} documents`, documentsCount: docsWithId.length });
} catch (error) {
console.error('Reindex error:', error);
res.status(500).json({ message: 'Reindex failed', error: error.message });
}
});
app.post('/knowledge-bases/:kbId/export', async (req, res) => {
try {
const { kbId } = req.params;
const { format } = req.body;
const kb = await KnowledgeBase.findOne({ _id: kbId });
if (!kb) {
return res.status(404).json({
success: false,
message: 'Knowledge base not found'
});
}
if (!await checkOrgAccess(kb.organizationId, req)) {
return res.status(403).json({ message: 'Access denied to this resource' });
}
const allDocs = await meilisearchClient.index(kb.meilisearchId).getDocuments({ limit: 10000 });
res.json({
success: true,
data: {
documents: allDocs.results || [],
total: allDocs.total || 0
}
});
} catch (error) {
console.error('Export error:', error);
res.status(500).json({
success: false,
message: 'Export failed',
error: error.message
});
}
});
app.listen(PORT, () => {
console.log(`🚀 Knowledge Base Service running on port ${PORT}`);
});
module.exports = app;
|