File size: 93,274 Bytes
064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 | /**
* Marketplace manager for Claude Code plugins
*
* This module provides functionality to:
* - Manage known marketplace sources (URLs, GitHub repos, npm packages, local files)
* - Cache marketplace manifests locally for offline access
* - Install plugins from marketplace entries
* - Track and update marketplace configurations
*
* File structure managed by this module:
* ~/.claude/
* βββ plugins/
* βββ known_marketplaces.json # Configuration of all known marketplaces
* βββ marketplaces/ # Cache directory for marketplace data
* βββ my-marketplace.json # Cached marketplace from URL source
* βββ github-marketplace/ # Cloned repository for GitHub source
* βββ .claude-plugin/
* βββ marketplace.json
*/
import axios from 'axios'
import { writeFile } from 'fs/promises'
import isEqual from 'lodash-es/isEqual.js'
import memoize from 'lodash-es/memoize.js'
import { basename, dirname, isAbsolute, join, resolve, sep } from 'path'
import { getFeatureValue_CACHED_MAY_BE_STALE } from '../../services/analytics/growthbook.js'
import { logForDebugging } from '../debug.js'
import { isEnvTruthy } from '../envUtils.js'
import {
ConfigParseError,
errorMessage,
getErrnoCode,
isENOENT,
toError,
} from '../errors.js'
import { execFileNoThrow, execFileNoThrowWithCwd } from '../execFileNoThrow.js'
import { getFsImplementation } from '../fsOperations.js'
import { gitExe } from '../git.js'
import { logError } from '../log.js'
import {
getInitialSettings,
getSettingsForSource,
updateSettingsForSource,
} from '../settings/settings.js'
import type { SettingsJson } from '../settings/types.js'
import {
jsonParse,
jsonStringify,
writeFileSync_DEPRECATED,
} from '../slowOperations.js'
import {
getAddDirEnabledPlugins,
getAddDirExtraMarketplaces,
} from './addDirPluginSettings.js'
import { markPluginVersionOrphaned } from './cacheUtils.js'
import { classifyFetchError, logPluginFetch } from './fetchTelemetry.js'
import { removeAllPluginsForMarketplace } from './installedPluginsManager.js'
import {
extractHostFromSource,
formatSourceForDisplay,
getHostPatternsFromAllowlist,
getStrictKnownMarketplaces,
isSourceAllowedByPolicy,
isSourceInBlocklist,
} from './marketplaceHelpers.js'
import {
OFFICIAL_MARKETPLACE_NAME,
OFFICIAL_MARKETPLACE_SOURCE,
} from './officialMarketplace.js'
import { fetchOfficialMarketplaceFromGcs } from './officialMarketplaceGcs.js'
import {
deletePluginDataDir,
getPluginSeedDirs,
getPluginsDirectory,
} from './pluginDirectories.js'
import { parsePluginIdentifier } from './pluginIdentifier.js'
import { deletePluginOptions } from './pluginOptionsStorage.js'
import {
isLocalMarketplaceSource,
type KnownMarketplace,
type KnownMarketplacesFile,
KnownMarketplacesFileSchema,
type MarketplaceSource,
type PluginMarketplace,
type PluginMarketplaceEntry,
PluginMarketplaceSchema,
validateOfficialNameSource,
} from './schemas.js'
/**
* Result of loading and caching a marketplace
*/
type LoadedPluginMarketplace = {
marketplace: PluginMarketplace
cachePath: string
}
/**
* Get the path to the known marketplaces configuration file
* Using a function instead of a constant allows proper mocking in tests
*/
function getKnownMarketplacesFile(): string {
return join(getPluginsDirectory(), 'known_marketplaces.json')
}
/**
* Get the path to the marketplaces cache directory
* Using a function instead of a constant allows proper mocking in tests
*/
export function getMarketplacesCacheDir(): string {
return join(getPluginsDirectory(), 'marketplaces')
}
/**
* Memoized inner function to get marketplace data.
* This caches the marketplace in memory after loading from disk or network.
*/
/**
* Clear all cached marketplace data (for testing)
*/
export function clearMarketplacesCache(): void {
getMarketplace.cache?.clear?.()
}
/**
* Configuration for known marketplaces
*/
export type KnownMarketplacesConfig = KnownMarketplacesFile
/**
* Declared marketplace entry (intent layer).
*
* Structurally compatible with settings `extraKnownMarketplaces` entries, but
* adds `sourceIsFallback` for implicit built-in declarations. This is NOT a
* settings-schema field β it's only ever set in code (never parsed from JSON).
*/
export type DeclaredMarketplace = {
source: MarketplaceSource
installLocation?: string
autoUpdate?: boolean
/**
* Presence suffices. When set, diffMarketplaces treats an already-materialized
* entry as upToDate regardless of source shape β never reports sourceChanged.
*
* Used for the implicit official-marketplace declaration: we want "clone from
* GitHub if missing", not "replace with GitHub if present under a different
* source". Without this, a seed dir that registers the official marketplace
* under e.g. an internal-mirror source would be stomped by a GitHub re-clone.
*/
sourceIsFallback?: boolean
}
/**
* Get declared marketplace intent from merged settings and --add-dir sources.
* This is what SHOULD exist β used by the reconciler to find gaps.
*
* The official marketplace is implicitly declared with `sourceIsFallback: true`
* when any enabled plugin references it.
*/
export function getDeclaredMarketplaces(): Record<string, DeclaredMarketplace> {
const implicit: Record<string, DeclaredMarketplace> = {}
// Only the official marketplace can be implicitly declared β it's the one
// built-in source we know. Other marketplaces have no default source to inject.
// Explicitly-disabled entries (value: false) don't count.
const enabledPlugins = {
...getAddDirEnabledPlugins(),
...(getInitialSettings().enabledPlugins ?? {}),
}
for (const [pluginId, value] of Object.entries(enabledPlugins)) {
if (
value &&
parsePluginIdentifier(pluginId).marketplace === OFFICIAL_MARKETPLACE_NAME
) {
implicit[OFFICIAL_MARKETPLACE_NAME] = {
source: OFFICIAL_MARKETPLACE_SOURCE,
sourceIsFallback: true,
}
break
}
}
// Lowest precedence: implicit < --add-dir < merged settings.
// An explicit extraKnownMarketplaces entry for claude-plugins-official
// in --add-dir or settings wins.
return {
...implicit,
...getAddDirExtraMarketplaces(),
...(getInitialSettings().extraKnownMarketplaces ?? {}),
}
}
/**
* Find which editable settings source declared a marketplace.
* Checks in reverse precedence order (highest priority last) so the
* result is the source that "wins" in the merged view.
* Returns null if the marketplace isn't declared in any editable source.
*/
export function getMarketplaceDeclaringSource(
name: string,
): 'userSettings' | 'projectSettings' | 'localSettings' | null {
// Check highest-precedence editable sources first β the one that wins
// in the merged view is the one we should write back to.
const editableSources: Array<
'localSettings' | 'projectSettings' | 'userSettings'
> = ['localSettings', 'projectSettings', 'userSettings']
for (const source of editableSources) {
const settings = getSettingsForSource(source)
if (settings?.extraKnownMarketplaces?.[name]) {
return source
}
}
return null
}
/**
* Save a marketplace entry to settings (intent layer).
* Does NOT touch known_marketplaces.json (state layer).
*
* @param name - The marketplace name
* @param entry - The marketplace config
* @param settingSource - Which settings source to write to (defaults to userSettings)
*/
export function saveMarketplaceToSettings(
name: string,
entry: DeclaredMarketplace,
settingSource:
| 'userSettings'
| 'projectSettings'
| 'localSettings' = 'userSettings',
): void {
const existing = getSettingsForSource(settingSource) ?? {}
const current = { ...existing.extraKnownMarketplaces }
current[name] = entry
updateSettingsForSource(settingSource, { extraKnownMarketplaces: current })
}
/**
* Load known marketplaces configuration from disk
*
* Reads the configuration file at ~/.claude/plugins/known_marketplaces.json
* which contains a mapping of marketplace names to their sources and metadata.
*
* Example configuration file content:
* ```json
* {
* "official-marketplace": {
* "source": { "source": "url", "url": "https://example.com/marketplace.json" },
* "installLocation": "/Users/me/.claude/plugins/marketplaces/official-marketplace.json",
* "lastUpdated": "2024-01-15T10:30:00.000Z"
* },
* "company-plugins": {
* "source": { "source": "github", "repo": "mycompany/plugins" },
* "installLocation": "/Users/me/.claude/plugins/marketplaces/company-plugins",
* "lastUpdated": "2024-01-14T15:45:00.000Z"
* }
* }
* ```
*
* @returns Configuration object mapping marketplace names to their metadata
*/
export async function loadKnownMarketplacesConfig(): Promise<KnownMarketplacesConfig> {
const fs = getFsImplementation()
const configFile = getKnownMarketplacesFile()
try {
const content = await fs.readFile(configFile, {
encoding: 'utf-8',
})
const data = jsonParse(content)
// Validate against schema
const parsed = KnownMarketplacesFileSchema().safeParse(data)
if (!parsed.success) {
const errorMsg = `Marketplace configuration file is corrupted: ${parsed.error.issues.map(e => `${e.path.join('.')}: ${e.message}`).join(', ')}`
logForDebugging(errorMsg, {
level: 'error',
})
throw new ConfigParseError(errorMsg, configFile, data)
}
return parsed.data
} catch (error) {
if (isENOENT(error)) {
return {}
}
// If it's already a ConfigParseError, re-throw it
if (error instanceof ConfigParseError) {
throw error
}
// For JSON parse errors or I/O errors, throw with helpful message
const errorMsg = `Failed to load marketplace configuration: ${errorMessage(error)}`
logForDebugging(errorMsg, {
level: 'error',
})
throw new Error(errorMsg)
}
}
/**
* Load known marketplaces config, returning {} on any error instead of throwing.
*
* Use this on read-only paths (plugin loading, feature checks) where a corrupted
* config should degrade gracefully rather than crash. DO NOT use on loadβmutateβsave
* paths β returning {} there would cause the save to overwrite the corrupted file
* with just the new entry, permanently destroying the user's other entries. The
* throwing variant preserves the file so the user can fix the corruption and recover.
*/
export async function loadKnownMarketplacesConfigSafe(): Promise<KnownMarketplacesConfig> {
try {
return await loadKnownMarketplacesConfig()
} catch {
// Inner function already logged via logForDebugging. Don't logError here β
// corrupted user config isn't a Claude Code bug, shouldn't hit the error file.
return {}
}
}
/**
* Save known marketplaces configuration to disk
*
* Writes the configuration to ~/.claude/plugins/known_marketplaces.json,
* creating the directory structure if it doesn't exist.
*
* @param config - The marketplace configuration to save
*/
export async function saveKnownMarketplacesConfig(
config: KnownMarketplacesConfig,
): Promise<void> {
// Validate before saving
const parsed = KnownMarketplacesFileSchema().safeParse(config)
const configFile = getKnownMarketplacesFile()
if (!parsed.success) {
throw new ConfigParseError(
`Invalid marketplace config: ${parsed.error.message}`,
configFile,
config,
)
}
const fs = getFsImplementation()
// Get directory from config file path to ensure consistency
const dir = join(configFile, '..')
await fs.mkdir(dir)
writeFileSync_DEPRECATED(configFile, jsonStringify(parsed.data, null, 2), {
encoding: 'utf-8',
flush: true,
})
}
/**
* Register marketplaces from the read-only seed directories into the primary
* known_marketplaces.json.
*
* The seed's known_marketplaces.json contains installLocation paths pointing
* into the seed dir itself. Registering those entries into the primary JSON
* makes them visible to all marketplace readers (getMarketplaceCacheOnly,
* getPluginByIdCacheOnly, etc.) without any loader changes β they just follow
* the installLocation wherever it points.
*
* Seed entries always win for marketplaces declared in the seed β the seed is
* admin-managed (baked into the container image). If admin updates the seed
* in a new image, those changes propagate on next boot. Users opt out of seed
* plugins via `plugin disable`, not by removing the marketplace.
*
* With multiple seed dirs (path-delimiter-separated), first-seed-wins: a
* marketplace name claimed by an earlier seed is skipped by later seeds.
*
* autoUpdate is forced to false since the seed is read-only and git-pull would
* fail. installLocation is computed from the runtime seedDir, not trusted from
* the seed's JSON (handles multi-stage Docker mount-path drift).
*
* Idempotent: second call with unchanged seed writes nothing.
*
* @returns true if any marketplace entries were written/changed (caller should
* clear caches so earlier plugin-load passes don't keep stale "marketplace
* not found" state)
*/
export async function registerSeedMarketplaces(): Promise<boolean> {
const seedDirs = getPluginSeedDirs()
if (seedDirs.length === 0) return false
const primary = await loadKnownMarketplacesConfig()
// First-seed-wins across this registration pass. Can't use the isEqual check
// alone β two seeds with the same name will have different installLocations.
const claimed = new Set<string>()
let changed = 0
for (const seedDir of seedDirs) {
const seedConfig = await readSeedKnownMarketplaces(seedDir)
if (!seedConfig) continue
for (const [name, seedEntry] of Object.entries(seedConfig)) {
if (claimed.has(name)) continue
// Compute installLocation relative to THIS seedDir, not the build-time
// path baked into the seed's JSON. Handles multi-stage Docker builds
// where the seed is mounted at a different path than where it was built.
const resolvedLocation = await findSeedMarketplaceLocation(seedDir, name)
if (!resolvedLocation) {
// Seed content missing (incomplete build) β leave primary alone, but
// don't claim the name either: a later seed may have working content.
logForDebugging(
`Seed marketplace '${name}' not found under ${seedDir}/marketplaces/, skipping`,
{ level: 'warn' },
)
continue
}
claimed.add(name)
const desired: KnownMarketplace = {
source: seedEntry.source,
installLocation: resolvedLocation,
lastUpdated: seedEntry.lastUpdated,
autoUpdate: false,
}
// Skip if primary already matches β idempotent no-op, no write.
if (isEqual(primary[name], desired)) continue
// Seed wins β admin-managed. Overwrite any existing primary entry.
primary[name] = desired
changed++
}
}
if (changed > 0) {
await saveKnownMarketplacesConfig(primary)
logForDebugging(`Synced ${changed} marketplace(s) from seed dir(s)`)
return true
}
return false
}
async function readSeedKnownMarketplaces(
seedDir: string,
): Promise<KnownMarketplacesConfig | null> {
const seedJsonPath = join(seedDir, 'known_marketplaces.json')
try {
const content = await getFsImplementation().readFile(seedJsonPath, {
encoding: 'utf-8',
})
const parsed = KnownMarketplacesFileSchema().safeParse(jsonParse(content))
if (!parsed.success) {
logForDebugging(
`Seed known_marketplaces.json invalid at ${seedDir}: ${parsed.error.message}`,
{ level: 'warn' },
)
return null
}
return parsed.data
} catch (e) {
if (!isENOENT(e)) {
logForDebugging(
`Failed to read seed known_marketplaces.json at ${seedDir}: ${e}`,
{ level: 'warn' },
)
}
return null
}
}
/**
* Locate a marketplace in the seed directory by name.
*
* Probes the canonical locations under seedDir/marketplaces/ rather than
* trusting the seed's stored installLocation (which may have a stale absolute
* path from a different build-time mount point).
*
* @returns Readable location, or null if neither format exists/validates
*/
async function findSeedMarketplaceLocation(
seedDir: string,
name: string,
): Promise<string | null> {
const dirCandidate = join(seedDir, 'marketplaces', name)
const jsonCandidate = join(seedDir, 'marketplaces', `${name}.json`)
for (const candidate of [dirCandidate, jsonCandidate]) {
try {
await readCachedMarketplace(candidate)
return candidate
} catch {
// Try next candidate
}
}
return null
}
/**
* If installLocation points into a configured seed directory, return that seed
* directory. Seed-managed entries are admin-controlled β users can't
* remove/refresh/modify them (they'd be overwritten by registerSeedMarketplaces
* on next startup). Returning the specific seed lets error messages name it.
*/
function seedDirFor(installLocation: string): string | undefined {
return getPluginSeedDirs().find(
d => installLocation === d || installLocation.startsWith(d + sep),
)
}
/**
* Git pull operation (exported for testing)
*
* Pulls latest changes with a configurable timeout (default 120s, override via CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS).
* Provides helpful error messages for common failure scenarios.
* If a ref is specified, fetches and checks out that specific branch or tag.
*/
// Environment variables to prevent git from prompting for credentials
const GIT_NO_PROMPT_ENV = {
GIT_TERMINAL_PROMPT: '0', // Prevent terminal credential prompts
GIT_ASKPASS: '', // Disable askpass GUI programs
}
const DEFAULT_PLUGIN_GIT_TIMEOUT_MS = 120 * 1000
function getPluginGitTimeoutMs(): number {
const envValue = process.env.CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS
if (envValue) {
const parsed = parseInt(envValue, 10)
if (!isNaN(parsed) && parsed > 0) {
return parsed
}
}
return DEFAULT_PLUGIN_GIT_TIMEOUT_MS
}
export async function gitPull(
cwd: string,
ref?: string,
options?: { disableCredentialHelper?: boolean; sparsePaths?: string[] },
): Promise<{ code: number; stderr: string }> {
logForDebugging(`git pull: cwd=${cwd} ref=${ref ?? 'default'}`)
const env = { ...process.env, ...GIT_NO_PROMPT_ENV }
const credentialArgs = options?.disableCredentialHelper
? ['-c', 'credential.helper=']
: []
if (ref) {
const fetchResult = await execFileNoThrowWithCwd(
gitExe(),
[...credentialArgs, 'fetch', 'origin', ref],
{ cwd, timeout: getPluginGitTimeoutMs(), stdin: 'ignore', env },
)
if (fetchResult.code !== 0) {
return enhanceGitPullErrorMessages(fetchResult)
}
const checkoutResult = await execFileNoThrowWithCwd(
gitExe(),
[...credentialArgs, 'checkout', ref],
{ cwd, timeout: getPluginGitTimeoutMs(), stdin: 'ignore', env },
)
if (checkoutResult.code !== 0) {
return enhanceGitPullErrorMessages(checkoutResult)
}
const pullResult = await execFileNoThrowWithCwd(
gitExe(),
[...credentialArgs, 'pull', 'origin', ref],
{ cwd, timeout: getPluginGitTimeoutMs(), stdin: 'ignore', env },
)
if (pullResult.code !== 0) {
return enhanceGitPullErrorMessages(pullResult)
}
await gitSubmoduleUpdate(cwd, credentialArgs, env, options?.sparsePaths)
return pullResult
}
const result = await execFileNoThrowWithCwd(
gitExe(),
[...credentialArgs, 'pull', 'origin', 'HEAD'],
{ cwd, timeout: getPluginGitTimeoutMs(), stdin: 'ignore', env },
)
if (result.code !== 0) {
return enhanceGitPullErrorMessages(result)
}
await gitSubmoduleUpdate(cwd, credentialArgs, env, options?.sparsePaths)
return result
}
/**
* Sync submodule working dirs after a successful pull. gitClone() uses
* --recurse-submodules, but gitPull() didn't β the parent repo's submodule
* pointer would advance while the working dir stayed at the old commit,
* making plugin sources in submodules unresolvable after marketplace update.
* Non-fatal: a failed submodule update logs a warning; most marketplaces
* don't use submodules at all. (gh-30696)
*
* Skipped for sparse clones β gitClone's sparse path intentionally omits
* --recurse-submodules to preserve partial-clone bandwidth savings, and
* .gitmodules is a root file that cone-mode sparse-checkout always
* materializes, so the .gitmodules gate alone can't distinguish sparse repos.
*
* Perf: git-submodule is a bash script that spawns ~20 subprocesses (~35ms+)
* even when no submodules exist. .gitmodules is a tracked file β pull
* materializes it iff the repo has submodules β so gate on its presence to
* skip the spawn for the common case.
*
* --init performs first-contact clone of newly-added submodules, so maintain
* parity with gitClone's non-sparse path: StrictHostKeyChecking=yes for
* fail-closed SSH (unknown hosts reject rather than silently populate
* known_hosts), and --depth 1 for shallow clone (matching --shallow-submodules).
* --depth only affects not-yet-initialized submodules; existing shallow
* submodules are unaffected.
*/
async function gitSubmoduleUpdate(
cwd: string,
credentialArgs: string[],
env: NodeJS.ProcessEnv,
sparsePaths: string[] | undefined,
): Promise<void> {
if (sparsePaths && sparsePaths.length > 0) return
const hasGitmodules = await getFsImplementation()
.stat(join(cwd, '.gitmodules'))
.then(
() => true,
() => false,
)
if (!hasGitmodules) return
const result = await execFileNoThrowWithCwd(
gitExe(),
[
'-c',
'core.sshCommand=ssh -o BatchMode=yes -o StrictHostKeyChecking=yes',
...credentialArgs,
'submodule',
'update',
'--init',
'--recursive',
'--depth',
'1',
],
{ cwd, timeout: getPluginGitTimeoutMs(), stdin: 'ignore', env },
)
if (result.code !== 0) {
logForDebugging(
`git submodule update failed (non-fatal): ${result.stderr}`,
{ level: 'warn' },
)
}
}
/**
* Enhance error messages for git pull failures
*/
function enhanceGitPullErrorMessages(result: {
code: number
stderr: string
error?: string
}): { code: number; stderr: string } {
if (result.code === 0) {
return result
}
// Detect execa timeout kills via the error field (stderr won't contain "timed out"
// when the process is killed by SIGTERM β the timeout info is only in error)
if (result.error?.includes('timed out')) {
const timeoutSec = Math.round(getPluginGitTimeoutMs() / 1000)
return {
...result,
stderr: `Git pull timed out after ${timeoutSec}s. Try increasing the timeout via CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS environment variable.\n\nOriginal error: ${result.stderr}`,
}
}
// Detect SSH host key verification failures (check before the generic
// 'Could not read from remote' catch β that string appears in both cases).
// OpenSSH emits "Host key verification failed" for BOTH host-not-in-known_hosts
// and host-key-has-changed β the latter also includes the "REMOTE HOST
// IDENTIFICATION HAS CHANGED" banner, which needs different remediation.
if (result.stderr.includes('REMOTE HOST IDENTIFICATION HAS CHANGED')) {
return {
...result,
stderr: `SSH host key for this marketplace's git host has changed (server key rotation or possible MITM). Remove the stale entry with: ssh-keygen -R <host>\nThen connect once manually to accept the new key.\n\nOriginal error: ${result.stderr}`,
}
}
if (result.stderr.includes('Host key verification failed')) {
return {
...result,
stderr: `SSH host key verification failed while updating marketplace. The host key is not in your known_hosts file. Connect once manually to add it (e.g., ssh -T git@<host>), or remove and re-add the marketplace with an HTTPS URL.\n\nOriginal error: ${result.stderr}`,
}
}
// Detect SSH authentication failures
if (
result.stderr.includes('Permission denied (publickey)') ||
result.stderr.includes('Could not read from remote repository')
) {
return {
...result,
stderr: `SSH authentication failed while updating marketplace. Please ensure your SSH keys are configured.\n\nOriginal error: ${result.stderr}`,
}
}
// Detect network issues
if (
result.stderr.includes('timed out') ||
result.stderr.includes('Could not resolve host')
) {
return {
...result,
stderr: `Network error while updating marketplace. Please check your internet connection.\n\nOriginal error: ${result.stderr}`,
}
}
return result
}
/**
* Check if SSH is likely to work for GitHub
* This is a quick heuristic check that avoids the full clone timeout
*
* Uses StrictHostKeyChecking=yes (not accept-new) so an unknown github.com
* host key fails closed rather than being silently added to known_hosts.
* This prevents a network-level MITM from poisoning known_hosts on first
* contact. Users who already have github.com in known_hosts see no change;
* users who don't are routed to the HTTPS clone path.
*
* @returns true if SSH auth succeeds and github.com is already trusted
*/
async function isGitHubSshLikelyConfigured(): Promise<boolean> {
try {
// Quick SSH connection test with 2 second timeout
// This fails fast if SSH isn't configured
const result = await execFileNoThrow(
'ssh',
[
'-T',
'-o',
'BatchMode=yes',
'-o',
'ConnectTimeout=2',
'-o',
'StrictHostKeyChecking=yes',
'git@github.com',
],
{
timeout: 3000, // 3 second total timeout
},
)
// SSH to github.com always returns exit code 1 with "successfully authenticated"
// or exit code 255 with "Permission denied" - we want the former
const configured =
result.code === 1 &&
(result.stderr?.includes('successfully authenticated') ||
result.stdout?.includes('successfully authenticated'))
logForDebugging(
`SSH config check: code=${result.code} configured=${configured}`,
)
return configured
} catch (error) {
// Any error means SSH isn't configured properly
logForDebugging(`SSH configuration check failed: ${errorMessage(error)}`, {
level: 'warn',
})
return false
}
}
/**
* Check if a git error indicates authentication failure.
* Used to provide enhanced error messages for auth failures.
*/
function isAuthenticationError(stderr: string): boolean {
return (
stderr.includes('Authentication failed') ||
stderr.includes('could not read Username') ||
stderr.includes('terminal prompts disabled') ||
stderr.includes('403') ||
stderr.includes('401')
)
}
/**
* Extract the SSH host from a git URL for error messaging.
* Matches the SSH format user@host:path (e.g., git@github.com:owner/repo.git).
*/
function extractSshHost(gitUrl: string): string | null {
const match = gitUrl.match(/^[^@]+@([^:]+):/)
return match?.[1] ?? null
}
/**
* Git clone operation (exported for testing)
*
* Clones a git repository with a configurable timeout (default 120s, override via CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS)
* and larger repositories. Provides helpful error messages for common failure scenarios.
* Optionally checks out a specific branch or tag.
*
* Does NOT disable credential helpers β this allows the user's existing auth setup
* (gh auth, keychain, git-credential-store, etc.) to work natively for private repos.
* Interactive prompts are still prevented via GIT_TERMINAL_PROMPT=0, GIT_ASKPASS='',
* stdin: 'ignore', and BatchMode=yes for SSH.
*
* Uses StrictHostKeyChecking=yes (not accept-new): unknown SSH hosts fail closed
* with a clear message rather than being silently trusted on first contact. For
* the github source type, the preflight check routes unknown-host users to HTTPS
* automatically; for explicit git@host:β¦ URLs, users see an actionable error.
*/
export async function gitClone(
gitUrl: string,
targetPath: string,
ref?: string,
sparsePaths?: string[],
): Promise<{ code: number; stderr: string }> {
const useSparse = sparsePaths && sparsePaths.length > 0
const args = [
'-c',
'core.sshCommand=ssh -o BatchMode=yes -o StrictHostKeyChecking=yes',
'clone',
'--depth',
'1',
]
if (useSparse) {
// Partial clone: skip blob download until checkout, defer checkout until
// after sparse-checkout is configured. Submodules are intentionally dropped
// for sparse clones β sparse monorepos rarely need them, and recursing
// submodules would defeat the partial-clone bandwidth savings.
args.push('--filter=blob:none', '--no-checkout')
} else {
args.push('--recurse-submodules', '--shallow-submodules')
}
if (ref) {
args.push('--branch', ref)
}
args.push(gitUrl, targetPath)
const timeoutMs = getPluginGitTimeoutMs()
logForDebugging(
`git clone: url=${redactUrlCredentials(gitUrl)} ref=${ref ?? 'default'} timeout=${timeoutMs}ms`,
)
const result = await execFileNoThrowWithCwd(gitExe(), args, {
timeout: timeoutMs,
stdin: 'ignore',
env: { ...process.env, ...GIT_NO_PROMPT_ENV },
})
// Scrub credentials from execa's error/stderr fields before any logging or
// returning. execa's shortMessage embeds the full command line (including
// the credentialed URL), and result.stderr may also contain it on some git
// versions.
const redacted = redactUrlCredentials(gitUrl)
if (gitUrl !== redacted) {
if (result.error) result.error = result.error.replaceAll(gitUrl, redacted)
if (result.stderr)
result.stderr = result.stderr.replaceAll(gitUrl, redacted)
}
if (result.code === 0) {
if (useSparse) {
// Configure the sparse cone, then materialize only those paths.
// `sparse-checkout set --cone` handles both init and path selection
// in a single step on git >= 2.25.
const sparseResult = await execFileNoThrowWithCwd(
gitExe(),
['sparse-checkout', 'set', '--cone', '--', ...sparsePaths],
{
cwd: targetPath,
timeout: timeoutMs,
stdin: 'ignore',
env: { ...process.env, ...GIT_NO_PROMPT_ENV },
},
)
if (sparseResult.code !== 0) {
return {
code: sparseResult.code,
stderr: `git sparse-checkout set failed: ${sparseResult.stderr}`,
}
}
const checkoutResult = await execFileNoThrowWithCwd(
gitExe(),
// ref was already passed to clone via --branch, so HEAD points to it;
// if no ref, HEAD points to the remote's default branch.
['checkout', 'HEAD'],
{
cwd: targetPath,
timeout: timeoutMs,
stdin: 'ignore',
env: { ...process.env, ...GIT_NO_PROMPT_ENV },
},
)
if (checkoutResult.code !== 0) {
return {
code: checkoutResult.code,
stderr: `git checkout after sparse-checkout failed: ${checkoutResult.stderr}`,
}
}
}
logForDebugging(`git clone succeeded: ${redactUrlCredentials(gitUrl)}`)
return result
}
logForDebugging(
`git clone failed: url=${redactUrlCredentials(gitUrl)} code=${result.code} error=${result.error ?? 'none'} stderr=${result.stderr}`,
{ level: 'warn' },
)
// Detect timeout kills β when execFileNoThrowWithCwd kills the process via SIGTERM,
// stderr may only contain partial output (e.g. "Cloning into '...'") with no
// "timed out" string. Check the error field from execa which contains the
// timeout message.
if (result.error?.includes('timed out')) {
return {
...result,
stderr: `Git clone timed out after ${Math.round(timeoutMs / 1000)}s. The repository may be too large for the current timeout. Set CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS to increase it (e.g., 300000 for 5 minutes).\n\nOriginal error: ${result.stderr}`,
}
}
// Enhance error messages for common scenarios
if (result.stderr) {
// Host key verification failure β check FIRST, before the generic
// 'Could not read from remote repository' catch (that string appears
// in both stderr outputs, so order matters). OpenSSH emits
// "Host key verification failed" for BOTH host-not-in-known_hosts and
// host-key-has-changed; distinguish them by the key-change banner.
if (result.stderr.includes('REMOTE HOST IDENTIFICATION HAS CHANGED')) {
const host = extractSshHost(gitUrl)
const removeHint = host ? `ssh-keygen -R ${host}` : 'ssh-keygen -R <host>'
return {
...result,
stderr: `SSH host key has changed (server key rotation or possible MITM). Remove the stale known_hosts entry:\n ${removeHint}\nThen connect once manually to verify and accept the new key.\n\nOriginal error: ${result.stderr}`,
}
}
if (result.stderr.includes('Host key verification failed')) {
const host = extractSshHost(gitUrl)
const connectHint = host ? `ssh -T git@${host}` : 'ssh -T git@<host>'
return {
...result,
stderr: `SSH host key is not in your known_hosts file. To add it, connect once manually (this will show the fingerprint for you to verify):\n ${connectHint}\n\nOr use an HTTPS URL instead (recommended for public repos).\n\nOriginal error: ${result.stderr}`,
}
}
if (
result.stderr.includes('Permission denied (publickey)') ||
result.stderr.includes('Could not read from remote repository')
) {
return {
...result,
stderr: `SSH authentication failed. Please ensure your SSH keys are configured for GitHub, or use an HTTPS URL instead.\n\nOriginal error: ${result.stderr}`,
}
}
if (isAuthenticationError(result.stderr)) {
return {
...result,
stderr: `HTTPS authentication failed. Please ensure your credential helper is configured (e.g., gh auth login).\n\nOriginal error: ${result.stderr}`,
}
}
if (
result.stderr.includes('timed out') ||
result.stderr.includes('timeout') ||
result.stderr.includes('Could not resolve host')
) {
return {
...result,
stderr: `Network error or timeout while cloning repository. Please check your internet connection and try again.\n\nOriginal error: ${result.stderr}`,
}
}
}
// Fallback for empty stderr β gh-28373: user saw "Failed to clone
// marketplace repository:" with nothing after the colon. Git CAN fail
// without writing to stderr (stdout instead, or output swallowed by
// credential helper / signal). execa's error field has the execa-level
// message (command, exit code, signal); exit code is the minimum.
if (!result.stderr) {
return {
code: result.code,
stderr:
result.error ||
`git clone exited with code ${result.code} (no stderr output). Run with --debug to see the full command.`,
}
}
return result
}
/**
* Progress callback for marketplace operations.
*
* This callback is invoked at various stages during marketplace operations
* (downloading, git operations, validation, etc.) to provide user feedback.
*
* IMPORTANT: Implementations should handle errors internally and not throw exceptions.
* If a callback throws, it will be caught and logged but won't abort the operation.
*
* @param message - Human-readable progress message to display to the user
*/
export type MarketplaceProgressCallback = (message: string) => void
/**
* Safely invoke a progress callback, catching and logging any errors.
* Prevents callback errors from aborting marketplace operations.
*
* @param onProgress - The progress callback to invoke
* @param message - Progress message to pass to the callback
*/
function safeCallProgress(
onProgress: MarketplaceProgressCallback | undefined,
message: string,
): void {
if (!onProgress) return
try {
onProgress(message)
} catch (callbackError) {
logForDebugging(`Progress callback error: ${errorMessage(callbackError)}`, {
level: 'warn',
})
}
}
/**
* Reconcile the on-disk sparse-checkout state with the desired config.
*
* Runs before gitPull to handle transitions:
* - FullβSparse or SparseAβSparseB: run `sparse-checkout set --cone` (idempotent)
* - SparseβFull: return non-zero so caller falls back to rm+reclone. Avoids
* `sparse-checkout disable` on a --filter=blob:none partial clone, which would
* trigger a lazy fetch of every blob in the monorepo.
* - FullβFull (common case): single local `git config --get` check, no-op.
*
* Failures here (ENOENT, not a repo) are harmless β gitPull will also fail and
* trigger the clone path, which establishes the correct state from scratch.
*/
export async function reconcileSparseCheckout(
cwd: string,
sparsePaths: string[] | undefined,
): Promise<{ code: number; stderr: string }> {
const env = { ...process.env, ...GIT_NO_PROMPT_ENV }
if (sparsePaths && sparsePaths.length > 0) {
return execFileNoThrowWithCwd(
gitExe(),
['sparse-checkout', 'set', '--cone', '--', ...sparsePaths],
{ cwd, timeout: getPluginGitTimeoutMs(), stdin: 'ignore', env },
)
}
const check = await execFileNoThrowWithCwd(
gitExe(),
['config', '--get', 'core.sparseCheckout'],
{ cwd, stdin: 'ignore', env },
)
if (check.code === 0 && check.stdout.trim() === 'true') {
return {
code: 1,
stderr:
'sparsePaths removed from config but repository is sparse; re-cloning for full checkout',
}
}
return { code: 0, stderr: '' }
}
/**
* Cache a marketplace from a git repository
*
* Clones or updates a git repository containing marketplace data.
* If the repository already exists at cachePath, pulls the latest changes.
* If pulling fails, removes the directory and re-clones.
*
* Example repository structure:
* ```
* my-marketplace/
* βββ .claude-plugin/
* β βββ marketplace.json # Default location for marketplace manifest
* βββ plugins/ # Plugin implementations
* βββ README.md
* ```
*
* @param gitUrl - The git URL to clone (https or ssh)
* @param cachePath - Local directory path to clone/update the repository
* @param ref - Optional git branch or tag to checkout
* @param onProgress - Optional callback to report progress
*/
async function cacheMarketplaceFromGit(
gitUrl: string,
cachePath: string,
ref?: string,
sparsePaths?: string[],
onProgress?: MarketplaceProgressCallback,
options?: { disableCredentialHelper?: boolean },
): Promise<void> {
const fs = getFsImplementation()
// Attempt incremental update; fall back to re-clone if the repo is absent,
// stale, or otherwise not updatable. Using pull-first avoids a stat-before-operate
// TOCTOU check: gitPull returns non-zero when cachePath is missing or has no .git.
const timeoutSec = Math.round(getPluginGitTimeoutMs() / 1000)
safeCallProgress(
onProgress,
`Refreshing marketplace cache (timeout: ${timeoutSec}s)β¦`,
)
// Reconcile sparse-checkout config before pulling. If this requires a re-clone
// (SparseβFull transition) or fails (missing dir, not a repo), skip straight
// to the rm+clone fallback.
const reconcileResult = await reconcileSparseCheckout(cachePath, sparsePaths)
if (reconcileResult.code === 0) {
const pullStarted = performance.now()
const pullResult = await gitPull(cachePath, ref, {
disableCredentialHelper: options?.disableCredentialHelper,
sparsePaths,
})
logPluginFetch(
'marketplace_pull',
gitUrl,
pullResult.code === 0 ? 'success' : 'failure',
performance.now() - pullStarted,
pullResult.code === 0 ? undefined : classifyFetchError(pullResult.stderr),
)
if (pullResult.code === 0) return
logForDebugging(`git pull failed, will re-clone: ${pullResult.stderr}`, {
level: 'warn',
})
} else {
logForDebugging(
`sparse-checkout reconcile requires re-clone: ${reconcileResult.stderr}`,
)
}
try {
await fs.rm(cachePath, { recursive: true })
// rm succeeded β a stale or partially-cloned directory existed; log for diagnostics
logForDebugging(
`Found stale marketplace directory at ${cachePath}, cleaning up to allow re-clone`,
{ level: 'warn' },
)
safeCallProgress(
onProgress,
'Found stale directory, cleaning up and re-cloningβ¦',
)
} catch (rmError) {
if (!isENOENT(rmError)) {
const rmErrorMsg = errorMessage(rmError)
throw new Error(
`Failed to clean up existing marketplace directory. Please manually delete the directory at ${cachePath} and try again.\n\nTechnical details: ${rmErrorMsg}`,
)
}
// ENOENT β cachePath didn't exist, this is a fresh install, nothing to clean up
}
// Clone the repository (one attempt β no internal retry loop)
const refMessage = ref ? ` (ref: ${ref})` : ''
safeCallProgress(
onProgress,
`Cloning repository (timeout: ${timeoutSec}s): ${redactUrlCredentials(gitUrl)}${refMessage}`,
)
const cloneStarted = performance.now()
const result = await gitClone(gitUrl, cachePath, ref, sparsePaths)
logPluginFetch(
'marketplace_clone',
gitUrl,
result.code === 0 ? 'success' : 'failure',
performance.now() - cloneStarted,
result.code === 0 ? undefined : classifyFetchError(result.stderr),
)
if (result.code !== 0) {
// Clean up any partial directory created by the failed clone so the next
// attempt starts fresh. Best-effort: if this fails, the stale dir will be
// auto-detected and removed at the top of the next call.
try {
await fs.rm(cachePath, { recursive: true, force: true })
} catch {
// ignore
}
throw new Error(`Failed to clone marketplace repository: ${result.stderr}`)
}
safeCallProgress(onProgress, 'Clone complete, validating marketplaceβ¦')
}
/**
* Redact header values for safe logging
*
* @param headers - Headers to redact
* @returns Headers with values replaced by '***REDACTED***'
*/
function redactHeaders(
headers: Record<string, string>,
): Record<string, string> {
return Object.fromEntries(
Object.entries(headers).map(([key]) => [key, '***REDACTED***']),
)
}
/**
* Redact userinfo (username:password) in a URL to avoid logging credentials.
*
* Marketplace URLs may embed credentials (e.g. GitHub PATs in
* `https://user:token@github.com/org/repo`). Debug logs and progress output
* are written to disk and may be included in bug reports, so credentials must
* be redacted before logging.
*
* Redacts all credentials from http(s) URLs:
* https://user:token@github.com/repo β https://***:***@github.com/repo
* https://:token@github.com/repo β https://:***@github.com/repo
* https://token@github.com/repo β https://***@github.com/repo
*
* Both username and password are redacted unconditionally on http(s) because
* it is impossible to distinguish `placeholder:secret` (e.g. x-access-token:ghp_...)
* from `secret:placeholder` (e.g. ghp_...:x-oauth-basic) by parsing alone.
* Non-http(s) schemes (ssh://git@...) and non-URL inputs (`owner/repo` shorthand)
* pass through unchanged.
*/
function redactUrlCredentials(urlString: string): string {
try {
const parsed = new URL(urlString)
const isHttp = parsed.protocol === 'http:' || parsed.protocol === 'https:'
if (isHttp && (parsed.username || parsed.password)) {
if (parsed.username) parsed.username = '***'
if (parsed.password) parsed.password = '***'
return parsed.toString()
}
} catch {
// Not a valid URL β safe as-is
}
return urlString
}
/**
* Cache a marketplace from a URL
*
* Downloads a marketplace.json file from a URL and saves it locally.
* Creates the cache directory structure if it doesn't exist.
*
* Example marketplace.json structure:
* ```json
* {
* "name": "my-marketplace",
* "owner": { "name": "John Doe", "email": "john@example.com" },
* "plugins": [
* {
* "id": "my-plugin",
* "name": "My Plugin",
* "source": "./plugins/my-plugin.json",
* "category": "productivity",
* "description": "A helpful plugin"
* }
* ]
* }
* ```
*
* @param url - The URL to download the marketplace.json from
* @param cachePath - Local file path to save the downloaded marketplace
* @param customHeaders - Optional custom HTTP headers for authentication
* @param onProgress - Optional callback to report progress
*/
async function cacheMarketplaceFromUrl(
url: string,
cachePath: string,
customHeaders?: Record<string, string>,
onProgress?: MarketplaceProgressCallback,
): Promise<void> {
const fs = getFsImplementation()
const redactedUrl = redactUrlCredentials(url)
safeCallProgress(onProgress, `Downloading marketplace from ${redactedUrl}`)
logForDebugging(`Downloading marketplace from URL: ${redactedUrl}`)
if (customHeaders && Object.keys(customHeaders).length > 0) {
logForDebugging(
`Using custom headers: ${jsonStringify(redactHeaders(customHeaders))}`,
)
}
const headers = {
...customHeaders,
// User-Agent must come last to prevent override (for consistency with WebFetch)
'User-Agent': 'Claude-Code-Plugin-Manager',
}
let response
const fetchStarted = performance.now()
try {
response = await axios.get(url, {
timeout: 10000,
headers,
})
} catch (error) {
logPluginFetch(
'marketplace_url',
url,
'failure',
performance.now() - fetchStarted,
classifyFetchError(error),
)
if (axios.isAxiosError(error)) {
if (error.code === 'ECONNREFUSED' || error.code === 'ENOTFOUND') {
throw new Error(
`Could not connect to ${redactedUrl}. Please check your internet connection and verify the URL is correct.\n\nTechnical details: ${error.message}`,
)
}
if (error.code === 'ETIMEDOUT') {
throw new Error(
`Request timed out while downloading marketplace from ${redactedUrl}. The server may be slow or unreachable.\n\nTechnical details: ${error.message}`,
)
}
if (error.response) {
throw new Error(
`HTTP ${error.response.status} error while downloading marketplace from ${redactedUrl}. The marketplace file may not exist at this URL.\n\nTechnical details: ${error.message}`,
)
}
}
throw new Error(
`Failed to download marketplace from ${redactedUrl}: ${errorMessage(error)}`,
)
}
safeCallProgress(onProgress, 'Validating marketplace data')
// Validate the response is a valid marketplace
const result = PluginMarketplaceSchema().safeParse(response.data)
if (!result.success) {
logPluginFetch(
'marketplace_url',
url,
'failure',
performance.now() - fetchStarted,
'invalid_schema',
)
throw new ConfigParseError(
`Invalid marketplace schema from URL: ${result.error.issues.map(e => `${e.path.join('.')}: ${e.message}`).join(', ')}`,
redactedUrl,
response.data,
)
}
logPluginFetch(
'marketplace_url',
url,
'success',
performance.now() - fetchStarted,
)
safeCallProgress(onProgress, 'Saving marketplace to cache')
// Ensure cache directory exists
const cacheDir = join(cachePath, '..')
await fs.mkdir(cacheDir)
// Write the validated marketplace file
writeFileSync_DEPRECATED(cachePath, jsonStringify(result.data, null, 2), {
encoding: 'utf-8',
flush: true,
})
}
/**
* Generate a cache path for a marketplace source
*/
function getCachePathForSource(source: MarketplaceSource): string {
const tempName =
source.source === 'github'
? source.repo.replace('/', '-')
: source.source === 'npm'
? source.package.replace('@', '').replace('/', '-')
: source.source === 'file'
? basename(source.path).replace('.json', '')
: source.source === 'directory'
? basename(source.path)
: 'temp_' + Date.now()
return tempName
}
/**
* Parse and validate JSON file with a Zod schema
*/
async function parseFileWithSchema<T>(
filePath: string,
schema: {
safeParse: (data: unknown) => {
success: boolean
data?: T
error?: {
issues: Array<{ path: PropertyKey[]; message: string }>
}
}
},
): Promise<T> {
const fs = getFsImplementation()
const content = await fs.readFile(filePath, { encoding: 'utf-8' })
let data: unknown
try {
data = jsonParse(content)
} catch (error) {
throw new ConfigParseError(
`Invalid JSON in ${filePath}: ${errorMessage(error)}`,
filePath,
content,
)
}
const result = schema.safeParse(data)
if (!result.success) {
throw new ConfigParseError(
`Invalid schema: ${filePath} ${result.error?.issues.map(e => `${e.path.join('.')}: ${e.message}`).join(', ')}`,
filePath,
data,
)
}
return result.data!
}
/**
* Load and cache a marketplace from its source
*
* Handles different source types:
* - URL: Downloads marketplace.json directly
* - GitHub: Clones repo and looks for .claude-plugin/marketplace.json
* - Git: Clones repository from git URL
* - NPM: (Not yet implemented) Would fetch from npm package
* - File: Reads from local filesystem
*
* After loading, validates the marketplace schema and renames the cache
* to match the marketplace's actual name from the manifest.
*
* Cache structure:
* ~/.claude/plugins/marketplaces/
* βββ official-marketplace.json # From URL source
* βββ github-marketplace/ # From GitHub/Git source
* β βββ .claude-plugin/
* β βββ marketplace.json
* βββ local-marketplace.json # From file source
*
* @param source - The marketplace source to load from
* @param onProgress - Optional callback to report progress
* @returns Object containing the validated marketplace and its cache path
* @throws If marketplace file not found or validation fails
*/
async function loadAndCacheMarketplace(
source: MarketplaceSource,
onProgress?: MarketplaceProgressCallback,
): Promise<LoadedPluginMarketplace> {
const fs = getFsImplementation()
const cacheDir = getMarketplacesCacheDir()
// Ensure cache directory exists
await fs.mkdir(cacheDir)
let temporaryCachePath: string
let marketplacePath: string
let cleanupNeeded = false
// Generate a temp name for the cache path
const tempName = getCachePathForSource(source)
try {
switch (source.source) {
case 'url': {
// Direct URL to marketplace.json
temporaryCachePath = join(cacheDir, `${tempName}.json`)
cleanupNeeded = true
await cacheMarketplaceFromUrl(
source.url,
temporaryCachePath,
source.headers,
onProgress,
)
marketplacePath = temporaryCachePath
break
}
case 'github': {
// Smart SSH/HTTPS selection: check if SSH is configured before trying it
// This avoids waiting for timeout on SSH when it's not configured
const sshUrl = `git@github.com:${source.repo}.git`
const httpsUrl = `https://github.com/${source.repo}.git`
temporaryCachePath = join(cacheDir, tempName)
cleanupNeeded = true
let lastError: Error | null = null
// Quick check if SSH is likely to work
const sshConfigured = await isGitHubSshLikelyConfigured()
if (sshConfigured) {
// SSH looks good, try it first
safeCallProgress(onProgress, `Cloning via SSH: ${sshUrl}`)
try {
await cacheMarketplaceFromGit(
sshUrl,
temporaryCachePath,
source.ref,
source.sparsePaths,
onProgress,
)
} catch (err) {
lastError = toError(err)
// Log SSH failure for monitoring
logError(lastError)
// SSH failed despite being configured, try HTTPS fallback
safeCallProgress(
onProgress,
`SSH clone failed, retrying with HTTPS: ${httpsUrl}`,
)
logForDebugging(
`SSH clone failed for ${source.repo} despite SSH being configured, falling back to HTTPS`,
{ level: 'info' },
)
// Clean up failed SSH attempt if it created anything
await fs.rm(temporaryCachePath, { recursive: true, force: true })
// Try HTTPS
try {
await cacheMarketplaceFromGit(
httpsUrl,
temporaryCachePath,
source.ref,
source.sparsePaths,
onProgress,
)
lastError = null // Success!
} catch (httpsErr) {
// HTTPS also failed - use HTTPS error as the final error
lastError = toError(httpsErr)
// Log HTTPS failure for monitoring (both SSH and HTTPS failed)
logError(lastError)
}
}
} else {
// SSH not configured, go straight to HTTPS
safeCallProgress(
onProgress,
`SSH not configured, cloning via HTTPS: ${httpsUrl}`,
)
logForDebugging(
`SSH not configured for GitHub, using HTTPS for ${source.repo}`,
{ level: 'info' },
)
try {
await cacheMarketplaceFromGit(
httpsUrl,
temporaryCachePath,
source.ref,
source.sparsePaths,
onProgress,
)
} catch (err) {
lastError = toError(err)
// Always try SSH as fallback for ANY HTTPS failure
// Log HTTPS failure for monitoring
logError(lastError)
// HTTPS failed, try SSH as fallback
safeCallProgress(
onProgress,
`HTTPS clone failed, retrying with SSH: ${sshUrl}`,
)
logForDebugging(
`HTTPS clone failed for ${source.repo} (${lastError.message}), falling back to SSH`,
{ level: 'info' },
)
// Clean up failed HTTPS attempt if it created anything
await fs.rm(temporaryCachePath, { recursive: true, force: true })
// Try SSH
try {
await cacheMarketplaceFromGit(
sshUrl,
temporaryCachePath,
source.ref,
source.sparsePaths,
onProgress,
)
lastError = null // Success!
} catch (sshErr) {
// SSH also failed - use SSH error as the final error
lastError = toError(sshErr)
// Log SSH failure for monitoring (both HTTPS and SSH failed)
logError(lastError)
}
}
}
// If we still have an error, throw it
if (lastError) {
throw lastError
}
marketplacePath = join(
temporaryCachePath,
source.path || '.claude-plugin/marketplace.json',
)
break
}
case 'git': {
temporaryCachePath = join(cacheDir, tempName)
cleanupNeeded = true
await cacheMarketplaceFromGit(
source.url,
temporaryCachePath,
source.ref,
source.sparsePaths,
onProgress,
)
marketplacePath = join(
temporaryCachePath,
source.path || '.claude-plugin/marketplace.json',
)
break
}
case 'npm': {
// TODO: Implement npm package support
throw new Error('NPM marketplace sources not yet implemented')
}
case 'file': {
// For local files, resolve paths relative to marketplace root directory
// File sources point to .claude-plugin/marketplace.json, so the marketplace
// root is two directories up (parent of .claude-plugin/)
// Resolve to absolute so error messages show the actual path checked
// (legacy known_marketplaces.json entries may have relative paths)
const absPath = resolve(source.path)
marketplacePath = absPath
temporaryCachePath = dirname(dirname(absPath))
cleanupNeeded = false
break
}
case 'directory': {
// For directories, look for .claude-plugin/marketplace.json
// Resolve to absolute so error messages show the actual path checked
// (legacy known_marketplaces.json entries may have relative paths)
const absPath = resolve(source.path)
marketplacePath = join(absPath, '.claude-plugin', 'marketplace.json')
temporaryCachePath = absPath
cleanupNeeded = false
break
}
case 'settings': {
// Inline manifest from settings.json β no fetch. Synthesize the
// marketplace.json on disk so getMarketplaceCacheOnly reads it
// like any other source. The plugins array already passed
// PluginMarketplaceEntrySchema validation when settings were parsed;
// the post-switch parseFileWithSchema re-validates the full
// PluginMarketplaceSchema (catches schema drift between the two).
//
// Writing to source.name up front means the rename below is a no-op
// (temporaryCachePath === finalCachePath). known_marketplaces.json
// stores this source object including the plugins array, so
// diffMarketplaces detects settings edits via isEqual β no special
// dirty-tracking needed.
temporaryCachePath = join(cacheDir, source.name)
marketplacePath = join(
temporaryCachePath,
'.claude-plugin',
'marketplace.json',
)
cleanupNeeded = false
await fs.mkdir(dirname(marketplacePath))
// No `satisfies PluginMarketplace` here: source.plugins is the narrow
// SettingsMarketplacePlugin type (no strict/.default(), no manifest
// fields). The parseFileWithSchema(PluginMarketplaceSchema()) call
// below widens and validates β that's the real check.
await writeFile(
marketplacePath,
jsonStringify(
{
name: source.name,
owner: source.owner ?? { name: 'settings' },
plugins: source.plugins,
},
null,
2,
),
)
break
}
default:
throw new Error(`Unsupported marketplace source type`)
}
// Load and validate the marketplace
logForDebugging(`Reading marketplace from ${marketplacePath}`)
let marketplace: PluginMarketplace
try {
marketplace = await parseFileWithSchema(
marketplacePath,
PluginMarketplaceSchema(),
)
} catch (e) {
if (isENOENT(e)) {
throw new Error(`Marketplace file not found at ${marketplacePath}`)
}
throw new Error(
`Failed to parse marketplace file at ${marketplacePath}: ${errorMessage(e)}`,
)
}
// Now rename the cache path to use the marketplace's actual name
const finalCachePath = join(cacheDir, marketplace.name)
// Defense-in-depth: the schema rejects path separators, .., and . in marketplace.name,
// but verify the computed path is a strict subdirectory of cacheDir before fs.rm.
// A malicious marketplace.json with a crafted name must never cause us to rm outside
// cacheDir, nor rm cacheDir itself (e.g. name "." β join normalizes to cacheDir).
const resolvedFinal = resolve(finalCachePath)
const resolvedCacheDir = resolve(cacheDir)
if (!resolvedFinal.startsWith(resolvedCacheDir + sep)) {
throw new Error(
`Marketplace name '${marketplace.name}' resolves to a path outside the cache directory`,
)
}
// Don't rename if it's a local file or directory, or already has the right name
if (
temporaryCachePath !== finalCachePath &&
!isLocalMarketplaceSource(source)
) {
try {
// Remove the destination if it already exists, then rename
try {
onProgress?.('Cleaning up old marketplace cacheβ¦')
} catch (callbackError) {
logForDebugging(
`Progress callback error: ${errorMessage(callbackError)}`,
{ level: 'warn' },
)
}
await fs.rm(finalCachePath, { recursive: true, force: true })
// Rename temp cache to final name
await fs.rename(temporaryCachePath, finalCachePath)
temporaryCachePath = finalCachePath
cleanupNeeded = false // Successfully renamed, no cleanup needed
} catch (error) {
const errorMsg = errorMessage(error)
throw new Error(
`Failed to finalize marketplace cache. Please manually delete the directory at ${finalCachePath} if it exists and try again.\n\nTechnical details: ${errorMsg}`,
)
}
}
return { marketplace, cachePath: temporaryCachePath }
} catch (error) {
// Clean up any temporary files/directories on error
if (
cleanupNeeded &&
temporaryCachePath! &&
!isLocalMarketplaceSource(source)
) {
try {
await fs.rm(temporaryCachePath!, { recursive: true, force: true })
} catch (cleanupError) {
logForDebugging(
`Warning: Failed to clean up temporary marketplace cache at ${temporaryCachePath}: ${errorMessage(cleanupError)}`,
{ level: 'warn' },
)
}
}
throw error
}
}
/**
* Add a marketplace source to the known marketplaces
*
* The marketplace is fetched, validated, and cached locally.
* The configuration is saved to ~/.claude/plugins/known_marketplaces.json.
*
* @param source - MarketplaceSource object representing the marketplace source.
* Callers should parse user input into MarketplaceSource format
* (see AddMarketplace.parseMarketplaceInput for handling shortcuts like "owner/repo").
* @param onProgress - Optional callback for progress updates during marketplace installation
* @throws If source format is invalid or marketplace cannot be loaded
*/
export async function addMarketplaceSource(
source: MarketplaceSource,
onProgress?: MarketplaceProgressCallback,
): Promise<{
name: string
alreadyMaterialized: boolean
resolvedSource: MarketplaceSource
}> {
// Resolve relative directory/file paths to absolute so state is cwd-independent
let resolvedSource = source
if (isLocalMarketplaceSource(source) && !isAbsolute(source.path)) {
resolvedSource = { ...source, path: resolve(source.path) }
}
// Check policy FIRST, before any network/filesystem operations
// This prevents downloading/cloning when the source is blocked
if (!isSourceAllowedByPolicy(resolvedSource)) {
// Check if explicitly blocked vs not in allowlist for better error messages
if (isSourceInBlocklist(resolvedSource)) {
throw new Error(
`Marketplace source '${formatSourceForDisplay(resolvedSource)}' is blocked by enterprise policy.`,
)
}
// Not in allowlist - build helpful error message
const allowlist = getStrictKnownMarketplaces() || []
const hostPatterns = getHostPatternsFromAllowlist()
const sourceHost = extractHostFromSource(resolvedSource)
let errorMessage = `Marketplace source '${formatSourceForDisplay(resolvedSource)}'`
if (sourceHost) {
errorMessage += ` (${sourceHost})`
}
errorMessage += ' is blocked by enterprise policy.'
if (allowlist.length > 0) {
errorMessage += ` Allowed sources: ${allowlist.map(s => formatSourceForDisplay(s)).join(', ')}`
} else {
errorMessage += ' No external marketplaces are allowed.'
}
// If source is a github shorthand and there are hostPatterns, suggest using full URL
if (resolvedSource.source === 'github' && hostPatterns.length > 0) {
errorMessage +=
`\n\nTip: The shorthand "${resolvedSource.repo}" assumes github.com. ` +
`For internal GitHub Enterprise, use the full URL:\n` +
` git@your-github-host.com:${resolvedSource.repo}.git`
}
throw new Error(errorMessage)
}
// Source-idempotency: if this exact source already exists, skip clone
const existingConfig = await loadKnownMarketplacesConfig()
for (const [existingName, existingEntry] of Object.entries(existingConfig)) {
if (isEqual(existingEntry.source, resolvedSource)) {
logForDebugging(
`Source already materialized as '${existingName}', skipping clone`,
)
return { name: existingName, alreadyMaterialized: true, resolvedSource }
}
}
// Load and cache the marketplace to validate it and get its name
const { marketplace, cachePath } = await loadAndCacheMarketplace(
resolvedSource,
onProgress,
)
// Validate that reserved names come from official sources
const sourceValidationError = validateOfficialNameSource(
marketplace.name,
resolvedSource,
)
if (sourceValidationError) {
throw new Error(sourceValidationError)
}
// Name collision with different source: overwrite (settings intent wins).
// Seed-managed entries are admin-controlled and cannot be overwritten.
// Re-read config after clone (may take a while; another process may have written).
const config = await loadKnownMarketplacesConfig()
const oldEntry = config[marketplace.name]
if (oldEntry) {
const seedDir = seedDirFor(oldEntry.installLocation)
if (seedDir) {
throw new Error(
`Marketplace '${marketplace.name}' is seed-managed (${seedDir}). ` +
`To use a different source, ask your admin to update the seed, ` +
`or use a different marketplace name.`,
)
}
logForDebugging(
`Marketplace '${marketplace.name}' exists with different source β overwriting`,
)
// Clean up the old cache if it's not a user-owned local path AND it
// actually differs from the new cachePath. loadAndCacheMarketplace writes
// to cachePath BEFORE we get here β rm-ing the same dir deletes the fresh
// write. Settings sources always land on the same dir (name β path);
// git sources hit this latently when the source repo changes but the
// fetched marketplace.json declares the same name. Only rm when locations
// genuinely differ (the only case where there's a stale dir to clean).
//
// Defensively validate the stored path before rm: a corrupted
// installLocation (gh-32793, gh-32661) could point at the user's project
// dir. If it's outside the cache dir, skip cleanup β the stale dir (if
// any) is harmless, and blocking the re-add would prevent the user from
// fixing the corruption.
if (!isLocalMarketplaceSource(oldEntry.source)) {
const cacheDir = resolve(getMarketplacesCacheDir())
const resolvedOld = resolve(oldEntry.installLocation)
const resolvedNew = resolve(cachePath)
if (resolvedOld === resolvedNew) {
// Same dir β loadAndCacheMarketplace already overwrote in place.
// Nothing to clean.
} else if (
resolvedOld === cacheDir ||
resolvedOld.startsWith(cacheDir + sep)
) {
const fs = getFsImplementation()
await fs.rm(oldEntry.installLocation, { recursive: true, force: true })
} else {
logForDebugging(
`Skipping cleanup of old installLocation (${oldEntry.installLocation}) β ` +
`outside ${cacheDir}. The path is corrupted; leaving it alone and ` +
`overwriting the config entry.`,
{ level: 'warn' },
)
}
}
}
// Update config using the marketplace's actual name
config[marketplace.name] = {
source: resolvedSource,
installLocation: cachePath,
lastUpdated: new Date().toISOString(),
}
await saveKnownMarketplacesConfig(config)
logForDebugging(`Added marketplace source: ${marketplace.name}`)
return { name: marketplace.name, alreadyMaterialized: false, resolvedSource }
}
/**
* Remove a marketplace source from known marketplaces
*
* Removes the marketplace configuration and cleans up cached files.
* Deletes both directory caches (for git sources) and file caches (for URL sources).
* Also cleans up the marketplace from settings.json (extraKnownMarketplaces) and
* removes related plugin entries from enabledPlugins.
*
* @param name - The marketplace name to remove
* @throws If marketplace with given name is not found
*/
export async function removeMarketplaceSource(name: string): Promise<void> {
const config = await loadKnownMarketplacesConfig()
if (!config[name]) {
throw new Error(`Marketplace '${name}' not found`)
}
// Seed-registered marketplaces are admin-baked into the container β removing
// them is a category error. They'd resurrect on next startup anyway. Guide
// the user to the right action instead.
const entry = config[name]
const seedDir = seedDirFor(entry.installLocation)
if (seedDir) {
throw new Error(
`Marketplace '${name}' is registered from the read-only seed directory ` +
`(${seedDir}) and will be re-registered on next startup. ` +
`To stop using its plugins: claude plugin disable <plugin>@${name}`,
)
}
// Remove from config
delete config[name]
await saveKnownMarketplacesConfig(config)
// Clean up cached files (both directory and JSON formats)
const fs = getFsImplementation()
const cacheDir = getMarketplacesCacheDir()
const cachePath = join(cacheDir, name)
await fs.rm(cachePath, { recursive: true, force: true })
const jsonCachePath = join(cacheDir, `${name}.json`)
await fs.rm(jsonCachePath, { force: true })
// Clean up settings.json - remove marketplace from extraKnownMarketplaces
// and remove related plugin entries from enabledPlugins
// Check each editable settings source
const editableSources: Array<
'userSettings' | 'projectSettings' | 'localSettings'
> = ['userSettings', 'projectSettings', 'localSettings']
for (const source of editableSources) {
const settings = getSettingsForSource(source)
if (!settings) continue
let needsUpdate = false
const updates: {
extraKnownMarketplaces?: typeof settings.extraKnownMarketplaces
enabledPlugins?: typeof settings.enabledPlugins
} = {}
// Remove from extraKnownMarketplaces if present
if (settings.extraKnownMarketplaces?.[name]) {
const updatedMarketplaces: Partial<
SettingsJson['extraKnownMarketplaces']
> = { ...settings.extraKnownMarketplaces }
// Use undefined values (NOT delete) to signal key removal via mergeWith
updatedMarketplaces[name] = undefined
updates.extraKnownMarketplaces =
updatedMarketplaces as SettingsJson['extraKnownMarketplaces']
needsUpdate = true
}
// Remove related plugins from enabledPlugins (format: "plugin@marketplace")
if (settings.enabledPlugins) {
const marketplaceSuffix = `@${name}`
const updatedPlugins = { ...settings.enabledPlugins }
let removedPlugins = false
for (const pluginId in updatedPlugins) {
if (pluginId.endsWith(marketplaceSuffix)) {
updatedPlugins[pluginId] = undefined
removedPlugins = true
}
}
if (removedPlugins) {
updates.enabledPlugins = updatedPlugins
needsUpdate = true
}
}
// Update settings if changes were made
if (needsUpdate) {
const result = updateSettingsForSource(source, updates)
if (result.error) {
logError(result.error)
logForDebugging(
`Failed to clean up marketplace '${name}' from ${source} settings: ${result.error.message}`,
)
} else {
logForDebugging(
`Cleaned up marketplace '${name}' from ${source} settings`,
)
}
}
}
// Remove plugins from installed_plugins.json and mark orphaned paths.
// Also wipe their stored options/secrets β after marketplace removal
// zero installations remain, same "last scope gone" condition as
// uninstallPluginOp.
const { orphanedPaths, removedPluginIds } =
removeAllPluginsForMarketplace(name)
for (const installPath of orphanedPaths) {
await markPluginVersionOrphaned(installPath)
}
for (const pluginId of removedPluginIds) {
deletePluginOptions(pluginId)
await deletePluginDataDir(pluginId)
}
logForDebugging(`Removed marketplace source: ${name}`)
}
/**
* Read a cached marketplace from disk without updating it
*
* @param installLocation - Path to the cached marketplace
* @returns The marketplace object
* @throws If marketplace file not found or invalid
*/
async function readCachedMarketplace(
installLocation: string,
): Promise<PluginMarketplace> {
// For git-sourced directories, the manifest lives at .claude-plugin/marketplace.json.
// For url/file/directory sources it is the installLocation itself.
// Try the nested path first; fall back to installLocation when it is a plain file
// (ENOTDIR) or the nested file is simply missing (ENOENT).
const nestedPath = join(installLocation, '.claude-plugin', 'marketplace.json')
try {
return await parseFileWithSchema(nestedPath, PluginMarketplaceSchema())
} catch (e) {
if (e instanceof ConfigParseError) throw e
const code = getErrnoCode(e)
if (code !== 'ENOENT' && code !== 'ENOTDIR') throw e
}
return await parseFileWithSchema(installLocation, PluginMarketplaceSchema())
}
/**
* Get a specific marketplace by name from cache only (no network).
* Returns null if cache is missing or corrupted.
* Use this for startup paths that should never block on network.
*/
export async function getMarketplaceCacheOnly(
name: string,
): Promise<PluginMarketplace | null> {
const fs = getFsImplementation()
const configFile = getKnownMarketplacesFile()
try {
const content = await fs.readFile(configFile, { encoding: 'utf-8' })
const config = jsonParse(content) as KnownMarketplacesConfig
const entry = config[name]
if (!entry) {
return null
}
return await readCachedMarketplace(entry.installLocation)
} catch (error) {
if (isENOENT(error)) {
return null
}
logForDebugging(
`Failed to read cached marketplace ${name}: ${errorMessage(error)}`,
{ level: 'warn' },
)
return null
}
}
/**
* Get a specific marketplace by name
*
* First attempts to read from cache. Only fetches from source if:
* - No cached version exists
* - Cache is invalid/corrupted
*
* This avoids unnecessary network/git operations on every access.
* Use refreshMarketplace() to explicitly update from source.
*
* @param name - The marketplace name to fetch
* @returns The marketplace object or null if not found/failed
*/
export const getMarketplace = memoize(
async (name: string): Promise<PluginMarketplace> => {
const config = await loadKnownMarketplacesConfig()
const entry = config[name]
if (!entry) {
throw new Error(
`Marketplace '${name}' not found in configuration. Available marketplaces: ${Object.keys(config).join(', ')}`,
)
}
// Legacy entries (pre-#19708) may have relative paths in global config.
// These are meaningless outside the project that wrote them β resolving
// against process.cwd() produces the wrong path. Give actionable guidance
// instead of a misleading ENOENT.
if (
isLocalMarketplaceSource(entry.source) &&
!isAbsolute(entry.source.path)
) {
throw new Error(
`Marketplace "${name}" has a relative source path (${entry.source.path}) ` +
`in known_marketplaces.json β this is stale state from an older ` +
`Claude Code version. Run 'claude marketplace remove ${name}' and ` +
`re-add it from the original project directory.`,
)
}
// Try to read from disk cache
try {
return await readCachedMarketplace(entry.installLocation)
} catch (error) {
// Log cache corruption before re-fetching
logForDebugging(
`Cache corrupted or missing for marketplace ${name}, re-fetching from source: ${errorMessage(error)}`,
{
level: 'warn',
},
)
}
// Cache doesn't exist or is invalid, fetch from source
let marketplace: PluginMarketplace
try {
;({ marketplace } = await loadAndCacheMarketplace(entry.source))
} catch (error) {
throw new Error(
`Failed to load marketplace "${name}" from source (${entry.source.source}): ${errorMessage(error)}`,
)
}
// Update lastUpdated only when we actually fetch
config[name]!.lastUpdated = new Date().toISOString()
await saveKnownMarketplacesConfig(config)
return marketplace
},
)
/**
* Get plugin by ID from cache only (no network calls).
* Returns null if marketplace cache is missing or corrupted.
* Use this for startup paths that should never block on network.
*
* @param pluginId - The plugin ID in format "name@marketplace"
* @returns The plugin entry or null if not found/cache missing
*/
export async function getPluginByIdCacheOnly(pluginId: string): Promise<{
entry: PluginMarketplaceEntry
marketplaceInstallLocation: string
} | null> {
const { name: pluginName, marketplace: marketplaceName } =
parsePluginIdentifier(pluginId)
if (!pluginName || !marketplaceName) {
return null
}
const fs = getFsImplementation()
const configFile = getKnownMarketplacesFile()
try {
const content = await fs.readFile(configFile, { encoding: 'utf-8' })
const config = jsonParse(content) as KnownMarketplacesConfig
const marketplaceConfig = config[marketplaceName]
if (!marketplaceConfig) {
return null
}
const marketplace = await getMarketplaceCacheOnly(marketplaceName)
if (!marketplace) {
return null
}
const plugin = marketplace.plugins.find(p => p.name === pluginName)
if (!plugin) {
return null
}
return {
entry: plugin,
marketplaceInstallLocation: marketplaceConfig.installLocation,
}
} catch {
return null
}
}
/**
* Get plugin by ID from a specific marketplace
*
* First tries cache-only lookup. If cache is missing/corrupted,
* falls back to fetching from source.
*
* @param pluginId - The plugin ID in format "name@marketplace"
* @returns The plugin entry or null if not found
*/
export async function getPluginById(pluginId: string): Promise<{
entry: PluginMarketplaceEntry
marketplaceInstallLocation: string
} | null> {
// Try cache-only first (fast path)
const cached = await getPluginByIdCacheOnly(pluginId)
if (cached) {
return cached
}
// Cache miss - try fetching from source
const { name: pluginName, marketplace: marketplaceName } =
parsePluginIdentifier(pluginId)
if (!pluginName || !marketplaceName) {
return null
}
try {
const config = await loadKnownMarketplacesConfig()
const marketplaceConfig = config[marketplaceName]
if (!marketplaceConfig) {
return null
}
const marketplace = await getMarketplace(marketplaceName)
const plugin = marketplace.plugins.find(p => p.name === pluginName)
if (!plugin) {
return null
}
return {
entry: plugin,
marketplaceInstallLocation: marketplaceConfig.installLocation,
}
} catch (error) {
logForDebugging(
`Could not find plugin ${pluginId}: ${errorMessage(error)}`,
{ level: 'debug' },
)
return null
}
}
/**
* Refresh all marketplace caches
*
* Updates all configured marketplaces from their sources.
* Continues refreshing even if some marketplaces fail.
* Updates lastUpdated timestamps for successful refreshes.
*
* This is useful for:
* - Periodic updates to get new plugins
* - Syncing after network connectivity is restored
* - Ensuring caches are up-to-date before browsing
*
* @returns Promise that resolves when all refresh attempts complete
*/
export async function refreshAllMarketplaces(): Promise<void> {
const config = await loadKnownMarketplacesConfig()
for (const [name, entry] of Object.entries(config)) {
// Seed-managed marketplaces are controlled by the seed image β refreshing
// them is pointless (registerSeedMarketplaces overwrites on next startup).
if (seedDirFor(entry.installLocation)) {
logForDebugging(
`Skipping seed-managed marketplace '${name}' in bulk refresh`,
)
continue
}
// settings-sourced marketplaces have no upstream β see refreshMarketplace.
if (entry.source.source === 'settings') {
continue
}
// inc-5046: same GCS intercept as refreshMarketplace() β bulk update
// hits this path on `claude plugin marketplace update` (no name arg).
if (name === OFFICIAL_MARKETPLACE_NAME) {
const sha = await fetchOfficialMarketplaceFromGcs(
entry.installLocation,
getMarketplacesCacheDir(),
)
if (sha !== null) {
config[name]!.lastUpdated = new Date().toISOString()
continue
}
if (
!getFeatureValue_CACHED_MAY_BE_STALE(
'tengu_plugin_official_mkt_git_fallback',
true,
)
) {
logForDebugging(
`Skipping official marketplace bulk refresh: GCS failed, git fallback disabled`,
)
continue
}
// fall through to git
}
try {
const { cachePath } = await loadAndCacheMarketplace(entry.source)
config[name]!.lastUpdated = new Date().toISOString()
config[name]!.installLocation = cachePath
} catch (error) {
logForDebugging(
`Failed to refresh marketplace ${name}: ${errorMessage(error)}`,
{
level: 'error',
},
)
}
}
await saveKnownMarketplacesConfig(config)
}
/**
* Refresh a single marketplace cache
*
* Updates a specific marketplace from its source by doing an in-place update.
* For git sources, runs git pull in the existing directory.
* For URL sources, re-downloads to the existing file.
* Clears the memoization cache and updates the lastUpdated timestamp.
*
* @param name - The name of the marketplace to refresh
* @param onProgress - Optional callback to report progress
* @throws If marketplace not found or refresh fails
*/
export async function refreshMarketplace(
name: string,
onProgress?: MarketplaceProgressCallback,
options?: { disableCredentialHelper?: boolean },
): Promise<void> {
const config = await loadKnownMarketplacesConfig()
const entry = config[name]
if (!entry) {
throw new Error(
`Marketplace '${name}' not found. Available marketplaces: ${Object.keys(config).join(', ')}`,
)
}
// Clear the memoization cache for this specific marketplace
getMarketplace.cache?.delete?.(name)
// settings-sourced marketplaces have no upstream to pull. Edits to the
// inline plugins array surface as sourceChanged in the reconciler, which
// re-materializes via addMarketplaceSource β refresh is not the vehicle.
if (entry.source.source === 'settings') {
logForDebugging(
`Skipping refresh for settings-sourced marketplace '${name}' β no upstream`,
)
return
}
try {
// For updates, use the existing installLocation directly (in-place update)
const installLocation = entry.installLocation
const source = entry.source
// Seed-managed marketplaces are controlled by the seed image. Refreshing
// would be pointless β registerSeedMarketplaces() overwrites installLocation
// back to seed on next startup. Error with guidance instead.
const seedDir = seedDirFor(installLocation)
if (seedDir) {
throw new Error(
`Marketplace '${name}' is seed-managed (${seedDir}) and its content is ` +
`controlled by the seed image. To update: ask your admin to update the seed.`,
)
}
// For remote sources (github/git/url), installLocation must be inside the
// marketplaces cache dir. A corrupted value (gh-32793, gh-32661 β e.g.
// Windows path read on WSL, literal tilde, manual edit) can point at the
// user's project. cacheMarketplaceFromGit would then run git ops with that
// cwd (git walks up to the user's .git) and fs.rm it on pull failure.
// Refuse instead of auto-fixing so the user knows their state is corrupted.
if (!isLocalMarketplaceSource(source)) {
const cacheDir = resolve(getMarketplacesCacheDir())
const resolvedLoc = resolve(installLocation)
if (resolvedLoc !== cacheDir && !resolvedLoc.startsWith(cacheDir + sep)) {
throw new Error(
`Marketplace '${name}' has a corrupted installLocation ` +
`(${installLocation}) β expected a path inside ${cacheDir}. ` +
`This can happen after cross-platform path writes or manual edits ` +
`to known_marketplaces.json. ` +
`Run: claude plugin marketplace remove "${name}" and re-add it.`,
)
}
}
// inc-5046: official marketplace fetches from a GCS mirror instead of
// git-cloning GitHub. Special-cased by NAME (not a new source type) so
// no data migration is needed β existing known_marketplaces.json entries
// still say source:'github', which is true (GCS is a mirror).
if (name === OFFICIAL_MARKETPLACE_NAME) {
const sha = await fetchOfficialMarketplaceFromGcs(
installLocation,
getMarketplacesCacheDir(),
)
if (sha !== null) {
config[name] = { ...entry, lastUpdated: new Date().toISOString() }
await saveKnownMarketplacesConfig(config)
return
}
// GCS failed β fall through to git ONLY if the kill-switch allows.
// Default true (backend write perms are pending as of inc-5046); flip
// to false via GrowthBook once the backend is confirmed live so new
// clients NEVER hit GitHub for the official marketplace.
if (
!getFeatureValue_CACHED_MAY_BE_STALE(
'tengu_plugin_official_mkt_git_fallback',
true,
)
) {
// Throw, don't return β every other failure path in this function
// throws, and callers like ManageMarketplaces.tsx:259 increment
// updatedCount on any non-throwing return. A silent return would
// report "Updated 1 marketplace" when nothing was refreshed.
throw new Error(
'Official marketplace GCS fetch failed and git fallback is disabled',
)
}
logForDebugging('Official marketplace GCS failed; falling back to git', {
level: 'warn',
})
// ...falls through to source.source === 'github' branch below
}
// Update based on source type
if (source.source === 'github' || source.source === 'git') {
// Git sources: do in-place git pull
if (source.source === 'github') {
// Same SSH/HTTPS fallback as loadAndCacheMarketplace: if the pull
// succeeds the remote URL in .git/config is used, but a re-clone
// needs a URL β pick the right protocol up-front and fall back.
const sshUrl = `git@github.com:${source.repo}.git`
const httpsUrl = `https://github.com/${source.repo}.git`
if (isEnvTruthy(process.env.CLAUDE_CODE_REMOTE)) {
// CCR: always HTTPS (no SSH keys available)
await cacheMarketplaceFromGit(
httpsUrl,
installLocation,
source.ref,
source.sparsePaths,
onProgress,
options,
)
} else {
const sshConfigured = await isGitHubSshLikelyConfigured()
const primaryUrl = sshConfigured ? sshUrl : httpsUrl
const fallbackUrl = sshConfigured ? httpsUrl : sshUrl
try {
await cacheMarketplaceFromGit(
primaryUrl,
installLocation,
source.ref,
source.sparsePaths,
onProgress,
options,
)
} catch {
logForDebugging(
`Marketplace refresh failed with ${sshConfigured ? 'SSH' : 'HTTPS'} for ${source.repo}, falling back to ${sshConfigured ? 'HTTPS' : 'SSH'}`,
{ level: 'info' },
)
await cacheMarketplaceFromGit(
fallbackUrl,
installLocation,
source.ref,
source.sparsePaths,
onProgress,
options,
)
}
}
} else {
// Explicit git URL: use as-is (no fallback available)
await cacheMarketplaceFromGit(
source.url,
installLocation,
source.ref,
source.sparsePaths,
onProgress,
options,
)
}
// Validate that marketplace.json still exists after update
// The repo may have been restructured or deprecated
try {
await readCachedMarketplace(installLocation)
} catch {
const sourceDisplay =
source.source === 'github'
? source.repo
: redactUrlCredentials(source.url)
const reason =
name === 'claude-code-plugins'
? `We've deprecated "claude-code-plugins" in favor of "claude-plugins-official".`
: `This marketplace may have been deprecated or moved to a new location.`
throw new Error(
`The marketplace.json file is no longer present in this repository.\n\n` +
`${reason}\n` +
`Source: ${sourceDisplay}\n\n` +
`You can remove this marketplace with: claude plugin marketplace remove "${name}"`,
)
}
} else if (source.source === 'url') {
// URL sources: re-download to existing file
await cacheMarketplaceFromUrl(
source.url,
installLocation,
source.headers,
onProgress,
)
} else if (isLocalMarketplaceSource(source)) {
// Local sources: no remote to update from, but validate the file still exists and is valid
safeCallProgress(onProgress, 'Validating local marketplace')
// Read and validate to ensure the marketplace file is still valid
await readCachedMarketplace(installLocation)
} else {
throw new Error(`Unsupported marketplace source type for refresh`)
}
// Update lastUpdated timestamp
config[name]!.lastUpdated = new Date().toISOString()
await saveKnownMarketplacesConfig(config)
logForDebugging(`Successfully refreshed marketplace: ${name}`)
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
logForDebugging(`Failed to refresh marketplace ${name}: ${errorMessage}`, {
level: 'error',
})
throw new Error(`Failed to refresh marketplace '${name}': ${errorMessage}`)
}
}
/**
* Set the autoUpdate flag for a marketplace
*
* When autoUpdate is enabled, the marketplace and its installed plugins
* will be automatically updated on startup.
*
* @param name - The name of the marketplace to update
* @param autoUpdate - Whether to enable auto-update
* @throws If marketplace not found
*/
export async function setMarketplaceAutoUpdate(
name: string,
autoUpdate: boolean,
): Promise<void> {
const config = await loadKnownMarketplacesConfig()
const entry = config[name]
if (!entry) {
throw new Error(
`Marketplace '${name}' not found. Available marketplaces: ${Object.keys(config).join(', ')}`,
)
}
// Seed-managed marketplaces always have autoUpdate: false (read-only, git-pull
// would fail). Toggle appears to work but registerSeedMarketplaces overwrites
// it on next startup. Error with guidance instead of silent revert.
const seedDir = seedDirFor(entry.installLocation)
if (seedDir) {
throw new Error(
`Marketplace '${name}' is seed-managed (${seedDir}) and ` +
`auto-update is always disabled for seed content. ` +
`To update: ask your admin to update the seed.`,
)
}
// Only update if the value is actually changing
if (entry.autoUpdate === autoUpdate) {
return
}
config[name] = {
...entry,
autoUpdate,
}
await saveKnownMarketplacesConfig(config)
// Also update intent in settings if declared there β write to the SAME
// source that declared it to avoid creating duplicates at wrong scope
const declaringSource = getMarketplaceDeclaringSource(name)
if (declaringSource) {
const declared =
getSettingsForSource(declaringSource)?.extraKnownMarketplaces?.[name]
if (declared) {
saveMarketplaceToSettings(
name,
{ source: declared.source, autoUpdate },
declaringSource,
)
}
}
logForDebugging(`Set autoUpdate=${autoUpdate} for marketplace: ${name}`)
}
export const _test = {
redactUrlCredentials,
}
|