Spaces:
Running
Running
File size: 106,596 Bytes
e8b33ca 1d919a0 e8b33ca | 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 | <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Hodge-3.5, the Encryptid EdgeAI assistant. A language model that runs on this device.">
<title>Hodge-3.5 · Encryptid EdgeAI</title>
<link rel="manifest" href="manifest.webmanifest">
<meta name="theme-color" content="#07090d">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="Hodge-3.5">
<link rel="icon" href="icons/icon-192.png">
<link rel="apple-touch-icon" href="icons/icon-192.png">
<style>
:root {
color-scheme: dark;
--bg: #07090d;
--ink: #ece7df;
--muted: #8e96a3;
--faint: #5e6673;
--copper: #e8a87c;
--copper-deep: #b8744a;
--line: rgba(232, 168, 124, 0.22);
--panel: rgba(12, 15, 22, 0.78);
--user: rgba(232, 168, 124, 0.14);
--err: #f0a8a0;
--ok: #d7c4ae;
}
* { box-sizing: border-box; }
[hidden] { display: none !important; }
html, body { height: 100%; margin: 0; }
body {
background:
radial-gradient(900px 480px at 100% -10%, rgba(232, 168, 124, 0.16), transparent 55%),
radial-gradient(700px 420px at -10% 110%, rgba(90, 110, 150, 0.14), transparent 50%),
var(--bg);
color: var(--ink);
font: 15px/1.5 "Segoe UI", system-ui, sans-serif;
}
button, textarea, input { font: inherit; color: inherit; }
button { cursor: pointer; }
button:disabled { cursor: default; opacity: 0.45; }
.top {
height: 58px; display: flex; align-items: center; gap: 14px;
padding: 0 22px; border-bottom: 1px solid rgba(255,255,255,0.06);
background: rgba(7, 9, 13, 0.72); backdrop-filter: blur(16px);
position: sticky; top: 0; z-index: 2;
}
.logo { letter-spacing: 0.18em; font-size: 12px; font-weight: 700; color: var(--copper); }
.product { font-size: 16px; font-weight: 650; letter-spacing: -0.02em; }
.mode-pick { position: relative; flex: 1; min-width: 0; display: flex; align-items: center; gap: 12px; }
#mode {
display: inline-flex; align-items: center; gap: 6px; min-width: 0; max-width: 100%;
border: 1px solid rgba(255,255,255,0.1); background: transparent; color: var(--muted);
border-radius: 999px; padding: 4px 10px 4px 12px; font-size: 13px;
}
#mode:not(:disabled):hover, #mode[aria-expanded="true"] { border-color: var(--line); color: var(--ink); }
#mode:disabled { opacity: 0.6; }
#mode b { font-weight: 600; color: var(--copper); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
#instrument {
border: 1px solid rgba(255,255,255,0.1); background: transparent; color: var(--muted);
border-radius: 999px; padding: 4px 10px; font-size: 12px; white-space: nowrap;
}
#instrument[aria-pressed="true"] { border-color: var(--line); color: var(--copper); }
#instrument[hidden] { display: none; }
#mode::after { content: "▾"; color: var(--faint); font-size: 11px; }
.mode-menu {
position: absolute; left: 0; top: calc(100% + 8px); z-index: 30; width: min(380px, 92vw);
display: grid; gap: 4px; padding: 6px; border-radius: 14px;
border: 1px solid var(--line); background: rgba(14, 17, 25, 0.98);
box-shadow: 0 16px 40px rgba(0,0,0,0.45);
}
.mode-menu[hidden] { display: none; }
.mode-menu button {
display: grid; gap: 2px; text-align: left; border: 1px solid transparent; background: transparent;
color: var(--ink); padding: 8px 10px; border-radius: 10px;
}
.mode-menu button:hover:not(:disabled), .mode-menu button:focus-visible { background: rgba(255,255,255,0.05); outline: none; }
.mode-menu button:disabled { opacity: 0.45; cursor: default; }
.mode-menu button[aria-checked="true"] { border-color: var(--line); }
.mode-menu button[aria-checked="true"] b { color: var(--copper); }
.mode-menu button span { color: var(--muted); font-size: 12px; }
.mode-menu button i { color: var(--faint); font-size: 11.5px; font-style: normal; }
.mode-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 4px; }
.mode-grid button { border-color: rgba(255,255,255,0.06); }
.mode-axes { display: flex; justify-content: space-between; color: var(--faint); font-size: 10.5px; letter-spacing: 0.08em; text-transform: uppercase; padding: 4px 4px 0; }
.mode-menu hr { border: 0; border-top: 1px solid rgba(255,255,255,0.06); margin: 2px; }
.ctx { display: inline-flex; align-items: center; gap: 6px; color: var(--faint); font-size: 11.5px; white-space: nowrap; }
.ctx[hidden] { display: none; }
.ctx i { width: 64px; height: 4px; border-radius: 99px; background: rgba(255,255,255,0.08); overflow: hidden; display: block; }
.ctx i b { display: block; height: 100%; width: 0; background: var(--copper); transition: width 0.3s; }
.ctx.warn { color: var(--copper); }
.handoff {
width: fit-content; max-width: min(640px, 100%); margin: 6px auto; padding: 4px 12px;
border: 1px dashed rgba(255,255,255,0.12); border-radius: 999px; color: var(--faint); font-size: 12px;
}
.status {
display: inline-flex; align-items: center; gap: 8px;
border: 1px solid rgba(255,255,255,0.08); border-radius: 999px;
padding: 5px 12px; font-size: 12px; color: var(--muted); white-space: nowrap;
}
.status i {
width: 7px; height: 7px; border-radius: 50%; background: var(--faint); display: block;
}
.status.busy { color: var(--copper); border-color: var(--line); }
.status.busy i { background: var(--copper); box-shadow: 0 0 10px var(--copper); animation: pulse 1.2s ease-in-out infinite; }
.status.ready { color: var(--ok); border-color: rgba(215, 196, 174, 0.35); }
.status.ready i { background: #c4a574; }
.status.fail { color: var(--err); border-color: rgba(240, 168, 160, 0.4); }
.status.fail i { background: var(--err); }
@keyframes pulse { 50% { opacity: 0.35; } }
@keyframes spin { to { transform: rotate(360deg); } }
.msg.assistant .bubble .load {
display: inline-flex; align-items: center; gap: 8px;
color: var(--copper); min-height: 1.4em; white-space: nowrap;
}
.msg.assistant .bubble .load i {
width: 14px; height: 14px; border-radius: 50%; flex: none;
border: 2px solid rgba(232, 168, 124, 0.28);
border-top-color: var(--copper);
background: transparent;
animation: spin 0.8s linear infinite;
}
.msg.assistant .bubble .lead { margin-bottom: 8px; white-space: pre-wrap; }
.app { display: grid; grid-template-columns: 280px minmax(0, 1fr); min-height: calc(100% - 58px); }
aside#side {
border-right: 1px solid rgba(255,255,255,0.06);
padding: 18px 16px 16px; display: flex; flex-direction: column; gap: 14px;
background: rgba(8, 10, 14, 0.45);
}
.new {
border: 1px solid var(--line); border-radius: 12px; padding: 10px 12px;
background: linear-gradient(180deg, rgba(232,168,124,0.2), rgba(232,168,124,0.05));
color: #ffe8d4; font-weight: 650;
}
.new:not(:disabled):hover { filter: brightness(1.08); }
.kicker { color: var(--faint); font-size: 11px; letter-spacing: 0.14em; text-transform: uppercase; }
.foot { margin-top: auto; color: var(--faint); font-size: 12px; letter-spacing: 0.04em; }
.foot a { color: inherit; }
main { display: flex; flex-direction: column; min-width: 0; min-height: 0; }
.stage { flex: 1; overflow: auto; }
.loading, .thread { width: min(760px, calc(100% - 40px)); margin: 0 auto; }
.loading {
min-height: calc(100vh - 180px); display: flex; flex-direction: column;
align-items: center; justify-content: center; text-align: center; gap: 8px;
}
.mark { font-size: 13px; letter-spacing: 0.2em; color: var(--copper); font-weight: 700; }
.loading h1 { margin: 0; font-size: 34px; font-weight: 640; letter-spacing: -0.03em; }
.loading p { margin: 0; color: var(--muted); max-width: 420px; }
.bar {
width: min(360px, 80%); height: 3px; margin-top: 18px; border-radius: 99px;
background: rgba(255,255,255,0.08); overflow: hidden;
}
.bar span {
display: block; height: 100%; width: 0%;
background: linear-gradient(90deg, var(--copper-deep), #ffe1c4);
box-shadow: 0 0 16px rgba(232, 168, 124, 0.7);
}
.thread { padding: 28px 0 12px; display: flex; flex-direction: column; gap: 16px; }
.msg { display: flex; }
.msg.user { justify-content: flex-end; }
.bubble {
max-width: min(640px, 100%); padding: 12px 14px; border-radius: 16px;
white-space: pre-wrap; word-break: break-word;
}
.msg.user .bubble { background: var(--user); border: 1px solid var(--line); border-bottom-right-radius: 5px; }
.msg.assistant .bubble {
background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.06);
border-bottom-left-radius: 5px;
}
.who { display: block; font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; color: var(--faint); margin-bottom: 4px; }
.meta { margin-top: 8px; color: var(--faint); font-size: 12px; }
.notice { color: var(--err); font-size: 13.5px; padding: 8px 2px; }
.chips { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; }
.chips button {
border: 1px solid rgba(255,255,255,0.1); background: rgba(255,255,255,0.03);
border-radius: 999px; padding: 8px 12px; color: var(--ink);
}
.chips button:hover { border-color: var(--line); }
.composer {
width: min(760px, calc(100% - 32px)); margin: 0 auto 18px;
display: flex; gap: 8px; align-items: flex-end;
padding: 8px; border-radius: 18px;
border: 1px solid var(--line);
background: rgba(10, 12, 18, 0.9);
box-shadow: 0 10px 40px rgba(0,0,0,0.35), inset 0 1px 0 rgba(255,255,255,0.04);
}
textarea {
flex: 1; resize: none; border: 0; background: transparent; outline: none;
padding: 10px 8px; max-height: 160px; min-height: 44px;
}
#send, #stop, #think {
border: 0; border-radius: 12px; padding: 10px 16px; font-weight: 650;
}
#agent-terms {
border: 1px solid var(--line); border-radius: 16px; padding: 22px 22px 18px;
width: min(520px, calc(100% - 32px)); background: #12151c; color: var(--ink);
}
#agent-terms::backdrop { background: rgba(4, 6, 10, 0.72); }
#agent-terms h2 { margin: 0 0 10px; font-size: 22px; font-weight: 640; letter-spacing: -0.03em; }
#agent-terms p { margin: 0 0 12px; color: var(--ink); }
#agent-terms a { color: var(--copper); }
.agent-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 6px; }
#agent-deny, #agent-accept {
border-radius: 12px; padding: 10px 16px; font-weight: 650;
}
#agent-deny {
border: 1px solid rgba(255,255,255,0.12); background: transparent; color: var(--muted);
}
#agent-accept {
border: 0; background: linear-gradient(180deg, #f0c7a4, #c4845a); color: #2a160c;
}
#agent-declined { color: var(--err); margin: 8px 0 0; }
#send { background: linear-gradient(180deg, #f0c7a4, #c4845a); color: #2a160c; }
#stop { background: #2a1614; color: var(--err); border: 1px solid rgba(240,168,160,0.35); }
#think {
border: 1px solid rgba(255,255,255,0.12);
background: transparent; color: var(--faint);
}
#think[aria-pressed="true"] {
color: #2a160c;
background: linear-gradient(180deg, #f0c7a4, #c4845a);
border-color: transparent;
}
#format {
border: 1px solid rgba(255,255,255,0.12); background: transparent;
color: var(--faint); border-radius: 12px; padding: 10px 8px; max-width: 7.5rem;
}
.compose-main { flex: 1; min-width: 0; display: flex; flex-direction: column; }
.compose-main textarea { flex: none; width: 100%; }
.tool-pick { position: relative; }
#plus {
width: 40px; height: 40px; border-radius: 12px; padding: 0;
border: 1px solid rgba(255,255,255,0.12); background: transparent;
color: var(--muted); font-size: 22px; line-height: 1;
}
#plus:not(:disabled):hover, #plus[aria-expanded="true"] { color: var(--ink); border-color: var(--line); }
.tool-menu {
position: absolute; left: 0; bottom: calc(100% + 8px); z-index: 20; min-width: 200px;
display: grid; gap: 2px; padding: 6px; border-radius: 14px;
border: 1px solid var(--line); background: rgba(14, 17, 25, 0.98);
box-shadow: 0 16px 40px rgba(0,0,0,0.45);
}
.tool-menu[hidden] { display: none; }
.tool-menu button {
display: flex; align-items: center; gap: 10px; text-align: left;
border: 0; background: transparent; color: var(--ink); padding: 8px 10px; border-radius: 9px;
}
.tool-menu button:hover, .tool-menu button:focus-visible { background: rgba(255,255,255,0.05); outline: none; }
.tool-menu button::before {
content: ""; width: 14px; height: 14px; flex: none; border-radius: 4px;
border: 1px solid rgba(255,255,255,0.25);
}
.tool-menu button[aria-checked="true"]::before {
border-color: transparent; background: linear-gradient(180deg, #f0c7a4, #c4845a);
}
.picked { display: flex; flex-wrap: wrap; gap: 6px; padding: 6px 6px 0; }
.picked[hidden] { display: none; }
.picked button {
border: 1px solid var(--line); background: rgba(240,199,164,0.08); color: var(--copper);
border-radius: 999px; padding: 3px 10px; font-size: 12.5px;
}
.picked button:hover { background: rgba(240,199,164,0.16); }
.media-note { font-size: 12px; color: var(--copper); margin-bottom: 4px; }
.thoughts { color: var(--muted); font-size: 13px; margin-bottom: 8px; }
.thoughts:empty { display: none; }
.tool {
max-width: min(640px, 100%); border: 1px solid rgba(255,255,255,0.08); border-radius: 14px;
background: rgba(12, 15, 22, 0.7); padding: 10px 12px; font-size: 13.5px;
}
.tool.bad { border-color: rgba(240, 168, 160, 0.3); }
.tool.ask { border-color: var(--line); }
.tool.skipped { opacity: 0.6; }
.tool-top { display: flex; gap: 10px; align-items: baseline; min-width: 0; }
.tool-top b { color: var(--copper); font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; white-space: nowrap; }
.tool-what { color: var(--muted); font-family: ui-monospace, Consolas, monospace; font-size: 12.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tool pre {
margin: 8px 0 0; padding: 8px 10px; border-radius: 9px; background: rgba(0,0,0,0.35);
font: 12.5px/1.45 ui-monospace, Consolas, monospace; white-space: pre-wrap; word-break: break-word;
max-height: 320px; overflow: auto;
}
.tool p { margin: 8px 0 0; color: var(--muted); }
.tool a { color: var(--copper); }
.tool .acts { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; }
.tool .acts button {
border: 1px solid rgba(255,255,255,0.12); background: transparent; border-radius: 10px; padding: 7px 12px;
}
.tool .acts button.go { background: linear-gradient(180deg, #f0c7a4, #c4845a); color: #2a160c; border-color: transparent; font-weight: 650; }
.tool.canvas {
max-width: min(720px, 100%); padding: 28px 32px 32px; font-size: 16.5px;
background: #f7f1e6; color: #1c140e; border-color: #e4d3bc;
}
.tool.canvas .tool-top b { color: #8a5a32; }
.tool.canvas .tool-what { display: none; }
.tool.canvas .md h3 { font-size: 26px; line-height: 1.2; color: #1c140e; margin: 4px 0 12px; }
.tool.canvas .md h4 { font-size: 18px; color: #1c140e; margin: 18px 0 6px; }
.tool.canvas .md p, .tool.canvas .md li { color: #2a2118; font-size: 16.5px; line-height: 1.5; }
.tool.canvas .md blockquote { color: #2a2118; border-left-color: #c4845a; }
.tool.canvas a { color: #8a3e12; }
.tool .md { margin-top: 6px; }
.tool .md h3, .tool .md h4, .tool .md h5 { margin: 10px 0 4px; font-weight: 650; letter-spacing: -0.01em; }
.tool .md h3 { font-size: 17px; } .tool .md h4 { font-size: 15px; } .tool .md h5 { font-size: 14px; color: var(--muted); }
.tool .md p { color: var(--ink); margin: 6px 0; }
.tool .md ul { margin: 6px 0; padding-left: 20px; }
.tool .md blockquote { margin: 6px 0; padding-left: 10px; border-left: 2px solid var(--line); color: var(--muted); }
.tool ul.tasks { list-style: none; margin: 8px 0 0; padding: 0; display: grid; gap: 5px; }
.tool .task { display: flex; gap: 10px; align-items: baseline; }
.tool .task-key { font-family: ui-monospace, Consolas, monospace; font-size: 12px; color: var(--faint); white-space: nowrap; }
.tool .task-state { font-size: 11px; border: 1px solid rgba(255,255,255,0.1); border-radius: 999px; padding: 0 7px; color: var(--muted); white-space: nowrap; }
.tool .task.done span:last-child { text-decoration: line-through; color: var(--faint); }
.tool .task.in_progress .task-state { color: var(--copper); border-color: var(--line); }
.menu { display: none; border: 0; background: transparent; font-size: 20px; padding: 4px 6px; color: var(--ink); }
aside { min-height: 0; overflow: hidden; }
.chat-search {
border: 1px solid rgba(255,255,255,0.08); border-radius: 10px; background: rgba(255,255,255,0.03);
padding: 8px 10px; font-size: 13.5px; outline: none;
}
.chat-search:focus { border-color: var(--line); }
.chats { flex: 1; min-height: 120px; overflow: auto; margin: 0 -6px; padding: 0 6px; }
.chats-group { color: var(--faint); font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; margin: 12px 6px 4px; }
.chats-empty { color: var(--faint); font-size: 13px; margin: 8px 6px; }
.chat-row { display: flex; align-items: center; border-radius: 9px; }
.chat-row:hover, .chat-row.on { background: rgba(255,255,255,0.05); }
.chat-row.on .chat-open { color: #ffe8d4; }
.chat-open {
flex: 1; min-width: 0; text-align: left; border: 0; background: transparent; padding: 7px 8px;
font-size: 13.5px; color: var(--ink); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.chat-act { border: 0; background: transparent; color: var(--faint); padding: 4px 6px; font-size: 12px; opacity: 0; }
.chat-row:hover .chat-act, .chat-row.on .chat-act, .chat-act:focus { opacity: 1; }
.chat-act:hover { color: var(--ink); }
.chat-act.armed { color: var(--err); opacity: 1; }
.chat-edit { flex: 1; min-width: 0; border: 1px solid var(--line); border-radius: 8px; background: rgba(0,0,0,0.3); padding: 6px 8px; font-size: 13.5px; outline: none; }
.stage { position: relative; }
.to-end {
position: sticky; bottom: 12px; left: calc(50% - 18px); width: 36px; height: 36px; border-radius: 50%;
border: 1px solid var(--line); background: rgba(10,12,18,0.92); color: var(--ink); display: block;
}
.msg { flex-direction: column; }
.msg.user { align-items: flex-end; }
.msg.assistant { align-items: flex-start; }
.msg.assistant .bubble { white-space: normal; }
.msg.assistant .bubble > div.live { white-space: pre-wrap; }
.acts-msg { display: flex; gap: 2px; margin-top: 4px; opacity: 0; transition: opacity 0.15s; }
.msg:hover .acts-msg, .msg:focus-within .acts-msg, .msg:last-child .acts-msg { opacity: 1; }
.acts-msg button { border: 0; background: transparent; color: var(--faint); font-size: 12px; padding: 3px 7px; border-radius: 7px; }
.acts-msg button:hover { color: var(--ink); background: rgba(255,255,255,0.05); }
.md > :first-child { margin-top: 0; }
.md > :last-child { margin-bottom: 0; }
.md p { margin: 0 0 10px; }
.md h3, .md h4, .md h5, .md h6, .md h7, .md h8 { margin: 16px 0 6px; font-weight: 650; letter-spacing: -0.01em; line-height: 1.3; }
.md h3 { font-size: 18px; } .md h4 { font-size: 16px; } .md h5, .md h6 { font-size: 15px; }
.md ul, .md ol { margin: 0 0 10px; padding-left: 22px; }
.md li { margin: 3px 0; }
.md li.task-item { list-style: none; margin-left: -18px; }
.md a { color: var(--copper); }
.md a.cite { font-size: 0.75em; vertical-align: super; margin-left: 2px; text-decoration: none; }
.md code { font: 0.9em ui-monospace, Consolas, monospace; background: rgba(255,255,255,0.07); padding: 1px 5px; border-radius: 5px; }
.md blockquote { margin: 0 0 10px; padding: 2px 0 2px 12px; border-left: 2px solid var(--line); color: var(--muted); }
.md hr { border: 0; border-top: 1px solid rgba(255,255,255,0.08); margin: 14px 0; }
.md .code { margin: 0 0 10px; border: 1px solid rgba(255,255,255,0.08); border-radius: 10px; overflow: hidden; background: rgba(0,0,0,0.38); }
.md .code-bar { display: flex; justify-content: space-between; align-items: center; padding: 5px 10px; font-size: 12px; color: var(--faint); background: rgba(255,255,255,0.03); }
.md .code-bar .copy { border: 0; background: transparent; color: var(--muted); font-size: 12px; padding: 2px 6px; }
.md .code-bar .copy:hover { color: var(--ink); }
.md .code pre { margin: 0; padding: 10px 12px; overflow-x: auto; }
.md .code code { background: none; padding: 0; font-size: 12.5px; line-height: 1.5; white-space: pre; }
.md .table { overflow-x: auto; margin: 0 0 10px; }
.md table { border-collapse: collapse; font-size: 13.5px; }
.md th, .md td { border: 1px solid rgba(255,255,255,0.1); padding: 5px 9px; text-align: left; vertical-align: top; }
.md th { background: rgba(255,255,255,0.04); font-weight: 600; }
.scrim { position: fixed; inset: 58px 0 0 0; background: rgba(0,0,0,0.5); z-index: 3; }
.app { height: calc(100% - 58px); }
#side { grid-column: 1; grid-row: 1; }
main { height: 100%; grid-column: 2; grid-row: 1; }
.app.mapped { grid-template-columns: 260px minmax(0, 1fr) minmax(300px, 440px); }
.map {
grid-column: 3; grid-row: 1; min-width: 0; min-height: 0;
display: flex; flex-direction: column;
border-left: 1px solid rgba(255,255,255,0.06);
background: rgba(8, 10, 14, 0.55);
}
.map-bar {
display: flex; flex-wrap: wrap; align-items: center; gap: 6px 8px; padding: 12px 12px 6px;
}
.map-bar .kicker { flex-basis: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.map-bar button {
border: 1px solid var(--line); background: transparent; border-radius: 999px;
padding: 2px 10px; font-size: 11px; letter-spacing: 0.04em; color: var(--copper);
}
.map-bar button[aria-pressed="false"] { color: var(--muted); border-color: rgba(255,255,255,0.1); }
#map-meta { margin-left: auto; color: var(--muted); font-size: 12px; text-align: right; }
.map canvas { flex: 1; width: 100%; min-height: 0; display: block; }
.map canvas[hidden] { display: none; }
.map-bar button:disabled { opacity: 0.4; cursor: not-allowed; }
.map-bar select {
background: rgba(8, 10, 14, 0.9); color: var(--ink); border: 1px solid rgba(255,255,255,0.12);
border-radius: 999px; padding: 2px 8px; font: inherit; font-size: 11px;
}
@media (max-width: 860px) {
.ctx { display: none; }
.menu { display: inline-block; }
.app { grid-template-columns: 1fr; }
aside#side {
position: fixed; top: 58px; bottom: 0; left: 0; width: min(300px, 86vw); z-index: 4;
background: #090b10; transform: translateX(-100%); transition: transform 0.2s ease;
}
aside#side.open { transform: none; }
.app.mapped { grid-template-columns: 1fr; grid-template-rows: minmax(210px, 36vh) minmax(0, 1fr); }
.app.mapped .map { grid-column: 1; grid-row: 1; border-left: 0; border-bottom: 1px solid rgba(255,255,255,0.06); }
.app.mapped main { grid-column: 1; grid-row: 2; height: auto; min-height: 0; }
.foot { margin-top: 0; }
.loading h1 { font-size: 28px; }
.loading, .thread { width: calc(100% - 32px); }
}
.thoughts > .load { display: flex; margin: 2px 0; }
@media (prefers-reduced-motion: reduce) {
.status.busy i, .load i { animation: none; }
}
</style>
</head>
<body>
<iframe id="local-frame" src="iwa/index.html?v=notab" hidden></iframe>
<header class="top">
<button id="menu" class="menu" type="button" aria-label="Chats" aria-expanded="false">☰</button>
<span class="logo">ENCRYPTID</span>
<span class="product">EdgeAI</span>
<div class="mode-pick">
<button id="mode" type="button" aria-haspopup="true" aria-expanded="false" aria-controls="mode-menu" title="Model" disabled><b id="mode-name">Hodge-3.5</b></button>
<div id="mode-menu" class="mode-menu" role="menu" aria-label="Model" hidden></div>
<span id="ctx" class="ctx" hidden><i><b id="ctx-fill"></b></i><span id="ctx-text"></span></span>
<button id="instrument" type="button" aria-pressed="false" title="Plain decode. Turn on for live currents on every token." hidden>Instrumented</button>
</div>
<span id="status" class="status busy"><i></i><span id="status-text">Starting</span></span>
</header>
<div class="app">
<aside id="side">
<button id="newchat" class="new" type="button" disabled>New chat</button>
<input id="chat-search" class="chat-search" type="search" placeholder="Search chats" aria-label="Search chats">
<nav id="chats" class="chats" aria-label="Chats"></nav>
<p class="foot"><a href="terms.html">Terms</a> · ai.encryptid.systems</p>
</aside>
<div id="scrim" class="scrim" hidden></div>
<main>
<div class="stage">
<div class="loading" id="loading">
<div class="mark">ENCRYPTID</div>
<p id="loading-copy">Bringing Hodge-3.5 onto this device.</p>
<div class="bar" id="bar" aria-hidden="true"><span id="bar-fill"></span></div>
</div>
<div class="thread" id="thread" hidden></div>
<button id="to-end" class="to-end" type="button" hidden aria-label="Scroll to the newest message">↓</button>
</div>
<form id="chat" class="composer">
<div class="tool-pick">
<button id="plus" type="button" aria-haspopup="true" aria-expanded="false" aria-controls="tool-menu" aria-label="Choose tools for Hodge-3.5" title="Choose tools" disabled>+</button>
<div id="tool-menu" class="tool-menu" role="group" aria-label="Tools" hidden></div>
</div>
<div class="compose-main">
<div id="picked" class="picked" aria-label="Chosen tools" hidden></div>
<div id="attached" class="picked" aria-label="Attached" hidden></div>
<input id="media-file" type="file" accept="image/*,audio/*" hidden>
<textarea id="msg" rows="1" placeholder="Message Hodge-3.5" autocomplete="off" disabled aria-label="Message"></textarea>
</div>
<select id="format" hidden aria-label="Chat format" title="Chat format"></select>
<button id="think" type="button" aria-pressed="false" disabled>Think</button>
<button id="stop" type="button" hidden>Stop</button>
<button id="send" type="submit" disabled>Send</button>
</form>
<dialog id="agent-terms" aria-labelledby="agent-title">
<h2 id="agent-title">Browser agent</h2>
<p>This is a browser agent. If you accept, Hodge-3.5 makes requests on your behalf from this browser. Those requests look things up, including DuckDuckGo, duck.ai, Gemini, and Wikipedia.</p>
<p>Accept and Hodge-3.5 starts. Deny and you cannot proceed. Hodge-3.5 does not start, and it makes no requests for you.</p>
<p><a href="terms.html">Terms of Service</a></p>
<div id="agent-choice" class="agent-actions">
<button id="agent-deny" type="button">Deny</button>
<button id="agent-accept" type="button">Accept</button>
</div>
<p id="agent-declined" hidden>You declined. You cannot proceed.</p>
</dialog>
</main>
<aside id="map" class="map" hidden aria-label="Instrumented Tensor Transformer">
<div class="map-bar">
<span class="kicker" title="Instrumented Tensor Transformer: the hot layer's currents, live">Instrumented Tensor Transformer</span>
<button id="map-follow" type="button" aria-pressed="true">Follow</button>
<span id="map-meta" aria-live="polite"></span>
</div>
<canvas id="map-canvas"></canvas>
</aside>
</div>
<script type="module">
// Encryptid EdgeAI. Champ loads on open. The runtime speaks JSON:
// stdout is one event per line, stdin is one command per line.
// ?prompt= is the first message. ?model= is an operator override.
import { PICKS, acceptsLearn, callAllowed, chatNote, clockText, declinesLearn, lookupQuery, pickedHint, playedTool, runTool, settleReply, slashCall, teachQuery, toolCallOf, toolStatus, toolStream, unknownReply, urlsIn, wantsLookup, wantsSavedNotes, wantsTeach } from "./ext.js?v=page";
import { createMind } from "./mind.js";
import { runChain, runPlan, sourceKept, wantsChain } from "./think.js?v=open2";
import { frameEcho } from "./frame.js?v=iwa";
import { createVM, vmEndpoint } from "./vm.js";
import { askConfirm, renderCard, resetAllow } from "./desk.js";
import { createLog } from "./persist.js";
import { createChats, inContextSummaryPrompt, rollPrompt, segmentPrompt, transcript } from "./chats.js";
import { renderMarkdown } from "./markdown.js?v=cite";
import { messageActions, renderChatList } from "./chatui.js";
import { createFlow } from "./flow.js";
import { DEPTH, ENGINES, KIND, RECIPE_SYSTEM, THINK_SYSTEM, TIERS, accept, admit, decide, factWhenUnnamed, join, named, nucleusCut, planOf, route, routeOf } from "./router.js?v=unnamed";
import { mountMap } from "./flowmap.js";
import { compile } from "/fastloader.js";
import { guestCore } from "./loader.js";
// The MVCC log is replayed before anything commits, so txn numbers continue.
const log = createLog();
const mind = createMind({ onCommit: (rec) => log.onCommit(rec) });
await log.load(mind);
mind.restoreModules();
const chats = createChats(mind);
let storage = null;
try { storage = localStorage; } catch { storage = null; }
// Nothing in the page's URL chooses what it loads or where it sends anything: the model is one the
// server's catalog lists (then the published copy, for champ), the arguments are fixed, and the exec
// endpoint is the local EncryptidVM unless this browser saved another.
const vm = createVM({ endpoint: vmEndpoint(storage), host: "" });
// The addresses gather may read: ones the person wrote, and ones a search listed.
const seenUrls = new Set();
function noteUrls(text) {
for (const u of urlsIn(text)) seenUrls.add(u);
}
const agentCtx = { vm, confirm: (cmd) => askConfirm(thread, cmd), known: (href) => seenUrls.has(href) };
async function runAgent(call) {
const ran = await runTool(call, undefined, agentCtx);
if (call && call.tool === "search" && ran) noteUrls(ran.output);
if (ran && /sign in required/i.test(ran.output || "")) {
location.href = "/auth/login?return_to=" + encodeURIComponent(location.pathname + location.search + location.hash);
}
return ran;
}
const here = new URL(".", location.href);
const WASM_URL = new URL("hkruntime.wasm?v=fmt1", here).href;
let wasmWarm = null;
function warmWasm() {
if (!wasmWarm) {
wasmWarm = compile(WASM_URL, { peel: guestCore }).catch((e) => {
wasmWarm = null;
throw e;
});
}
return wasmWarm;
}
const KERNELS = ["hodgelinear", "norm", "rope", "attention", "embed", "lmhead", "dot4_native", "dot4_soft", "wedge", "wedgezero",
"encprep", "encmatmul", "encpost", "encqk", "encattn", "encpos", "encpool",
"encconv2d", "encrelpos", "encrelattn", "encdwconv"];
// A model folder with volume.safetensors is instrumented: live cell currents, drawn as the Instrumented Tensor Transformer map.
let flow = createFlow(false);
let map = null;
let flowToken = "";
// Plain decode until this browser asks for live currents. The instrumented body still loads
// when the folder has a volume, so the switch does not reload the weights.
let instrument = false;
try { instrument = localStorage.getItem("champ.instrument") === "1"; } catch { instrument = false; }
const FLOW_KERNELS = ["flow", "flowscale", "cellsum"];
function paintInstrument() {
const b = $("instrument");
b.hidden = !flow.on;
b.setAttribute("aria-pressed", instrument ? "true" : "false");
b.title = instrument
? "Live currents on every token."
: "Plain decode. Turn on for live currents on every token.";
const show = flow.on && instrument;
document.querySelector(".app").classList.toggle("mapped", show);
$("map").hidden = !show;
}
function armFlow() {
if (!flow.on) {
flow = createFlow(true);
for (const k of FLOW_KERNELS) if (!KERNELS.includes(k)) KERNELS.push(k);
if (!map) map = mountMap($("map"));
flow.listen((fr) => map.frame(fr));
}
paintInstrument();
}
// A model without volume.safetensors runs uninstrumented: no flow files, no flow kernels, no map.
function disarmFlow() {
flow = createFlow(false);
for (const k of FLOW_KERNELS) {
const i = KERNELS.indexOf(k);
if (i >= 0) KERNELS.splice(i, 1);
}
paintInstrument();
}
const SMALL = ["config.json", "generation_config.json", "tokenizer.json", "tokenizer_config.json"];
// Short and stated positively: a 2B model follows a few plain instructions far
// better than a list of prohibitions, and each "do not X" puts X in its context.
// A demand for concrete detail is how this checkpoint fills a gap with a river,
// a year, or a city. The catalog name is filled in once the model is chosen.
function systemText(name) {
const who = String(name || "Hodge-4").slice(0, 40);
return "You are " + who + ", a helpful assistant that runs on this device. You are a model developed by Encryptid Systems. Answer the person's question. State a fact only when you are sure of it. When you are not sure, say so in one sentence. Keep the answer short unless the person asks for a long one.";
}
// Earlier defaults, which a saved prompt may still hold. The long one asked
// for concrete detail the checkpoint does not have.
const OLD_SYSTEM = /^You are Hodge(?:-3\.5|-4)?, (?:the auditable model\b|a helpful assistant that runs on this device\. (?:Answer the person's message directly|Give complete, well-organized answers|Write long, thorough, in-depth answers))/;
// The system prompt is the person's to edit (the System prompt button): kept in this browser as
// "champ.system", the catalog model's short default otherwise.
// A stored prompt that still names Champ is the old default, so it is dropped.
const SYSTEM_MAX = 8000;
let systemCustom = false;
function savedSystem() {
try {
const s = localStorage.getItem("champ.system");
// The old default named Champ or spelled out every tool, including canvas.
if (s && s.trim() && !/\bchamp\b/i.test(s) && !/"tool"\s*:\s*"canvas"/.test(s) && !OLD_SYSTEM.test(s.trim())) {
systemCustom = true;
return s.slice(0, SYSTEM_MAX);
}
if (s) localStorage.removeItem("champ.system");
} catch { /* storage off */ }
systemCustom = false;
return systemText("Hodge-4");
}
let SYSTEM = savedSystem();
const $ = (id) => document.getElementById(id);
$("instrument").onclick = () => {
instrument = !instrument;
try { localStorage.setItem("champ.instrument", instrument ? "1" : "0"); } catch { /* this visit only */ }
paintInstrument();
};
const statusEl = $("status");
const statusText = $("status-text");
function status(t, kind) {
statusText.textContent = t;
statusEl.className = "status " + (kind || "");
}
// 4 MiB: a chat command can carry 30 s of audio tower tokens (about 1.9 MB of base64).
const sab = new SharedArrayBuffer(1 << 22);
const i32 = new Int32Array(sab);
const u8 = new Uint8Array(sab);
const stopSab = new SharedArrayBuffer(1);
const stopByte = new Uint8Array(stopSab);
function stdin(text) {
const b = new TextEncoder().encode(text);
const n = Atomics.load(i32, 1);
if (16 + n + b.length > u8.length) return false;
u8.set(b, 16 + n);
Atomics.store(i32, 1, n + b.length);
Atomics.store(i32, 0, 1);
Atomics.notify(i32, 0);
return true;
}
// The chat whose turns are in the model's context, the first message seq of
// the stretch since the last reset, and the context fill from the last answer.
let chatId = null;
let primedId = null;
let segFrom = 0;
let ctxPos = 0;
let ctxMax = 0;
let pendingPrefix = "";
let lastChatCmd = null;
let chatFormat = "";
function setFormats(list, current, rope) {
const sel = $("format");
const formats = Array.isArray(list) ? list.filter((x) => typeof x === "string" && x) : [];
const ropeNote = rope && rope.type && rope.type !== "none"
? "RoPE " + rope.type + " ×" + rope.factor
: "RoPE none";
sel.title = ropeNote;
if (formats.length < 2) {
sel.hidden = true;
sel.innerHTML = "";
chatFormat = "";
return;
}
sel.innerHTML = "";
for (const name of formats) {
const o = document.createElement("option");
o.value = name;
o.textContent = name;
sel.appendChild(o);
}
sel.value = formats.indexOf(current) >= 0 ? current : formats[0];
chatFormat = sel.value;
sel.hidden = false;
}
$("format").onchange = () => { chatFormat = $("format").value; };
// A nucleus cut stops this sample only. A person stop still ends the turn.
let nucleusHold = false;
let userStop = false;
// Most tokens in one answer when the command names no max. The end token
// normally comes first; this only bounds a run that never finds it.
const ANSWER_MAX = 2048;
// The guest's own defaults until the ready event reports generation_config.
let sampleDefaults = { temp: 0.6, top_p: 0.9, min_p: 0.1, repeat: 1.08 };
// A factual write stays near the mode. The wide nucleus is where the invented
// detail was being drawn from.
const FACT_SAMPLE = { temp: 0.2, top_p: 0.75, min_p: 0.2, repeat: 1.12 };
let compacting = false;
let silentReset = null;
let editFrom = null;
// A chat command carries the gathered context once, on the first turn after a rebuild.
function command(obj) {
if (obj.op === "chat") {
if (chatFormat) obj.format = chatFormat;
obj.flow = !!(flow.on && instrument);
// Sampling is the model's generation_config, unless this turn names its
// own. A factual write passes a tighter sample. The values are sent on
// every turn so a tight sample does not stick to the next chat.
const sample = obj.sample || sampleDefaults;
delete obj.sample;
if (obj.temp == null && Number.isFinite(sample.temp) && sample.temp >= 0) obj.temp = sample.temp;
if (obj.top_p == null && Number.isFinite(sample.top_p) && sample.top_p > 0 && sample.top_p <= 1) obj.top_p = sample.top_p;
if (obj.min_p == null && Number.isFinite(sample.min_p) && sample.min_p >= 0 && sample.min_p < 1) obj.min_p = sample.min_p;
if (obj.repeat == null && Number.isFinite(sample.repeat) && sample.repeat >= 1) obj.repeat = sample.repeat;
if (typeof obj.max !== "number") obj.max = ANSWER_MAX;
lastChatCmd = obj;
if (pendingPrefix) {
obj = Object.assign({}, obj, { text: pendingPrefix + "\n\n" + obj.text });
pendingPrefix = "";
}
}
return stdin(JSON.stringify(obj) + "\n");
}
// Clears the model's context without touching the page.
function resetModel() {
return new Promise((resolve) => {
silentReset = resolve;
if (!command({ op: "reset" })) {
silentReset = null;
resolve();
}
});
}
// The server lists its models in /models/catalog.json, {"models":[{"id":"hodge-4","name":"Hodge-4"}, ...]},
// and each one is the folder /models/<id>/. The page loads only an id that list names; no URL parameter
// picks a model, and the choice is this browser's own (localStorage "champ.model"). With no list there is
// one model, /models/champ/.
const MODEL_ID = /^[a-z0-9][a-z0-9-]{0,31}$/;
let modelId = "hodge-1";
let modelCount = 0;
async function catalog() {
try {
const r = await fetch(new URL("/models/catalog.json", location.href), { cache: "no-store" });
const type = r.headers.get("Content-Type") || "";
if (!r.ok || type.includes("text/html")) return [];
const j = await r.json();
const seen = new Set();
const out = [];
for (const m of Array.isArray(j && j.models) ? j.models : []) {
if (!m || typeof m.id !== "string" || !MODEL_ID.test(m.id) || seen.has(m.id)) continue;
seen.add(m.id);
const name = typeof m.name === "string" && m.name.trim() ? m.name.trim().slice(0, 80) : m.id;
// tier: the engine slot Auto routes to (router.js): lite, balanced, thinking or pro.
const tier = typeof m.tier === "string" && TIERS.has(m.tier) ? m.tier : "";
out.push({ id: m.id, name, tier });
}
return out;
} catch {
return [];
}
}
// The header's model menu: Auto (the router) or one model. The choice is this browser's own
// (localStorage "champ.mode": "auto" or a catalog id).
let models = [];
let mode = "auto";
async function pickModel() {
const list = await catalog();
modelCount = list.length;
models = list;
if (!list.length) {
models = [{ id: "hodge-1", name: "Hodge-3.5", tier: "lite" }];
mode = "hodge-1";
modelId = "hodge-1";
renderModes();
return new URL("/models/hodge-1/", location.href).href;
}
let want = "";
try { want = localStorage.getItem("champ.mode") || localStorage.getItem("champ.model") || ""; } catch { want = ""; }
const tiered = list.some((m) => m.tier);
mode = want === "auto" || (!want && tiered) ? "auto" : (list.find((m) => m.id === want) || list[0]).id;
if (mode === "auto" && !tiered) mode = list[0].id;
// Auto starts on the Lite engine, the quickest to load, when the server has one.
const first = mode === "auto" ? (list.find((m) => m.tier === "lite") || list.find((m) => m.tier)) : list.find((m) => m.id === mode);
modelId = first.id;
if (!systemCustom) SYSTEM = systemText(first.name);
renderModes();
return new URL("/models/" + first.id + "/", location.href).href;
}
function modelOf(id) {
return models.find((m) => m.id === id) || null;
}
function engineOf(m) {
return (m && ENGINES.find((e) => e.tier === m.tier)) || null;
}
function shownName() {
const m = modelOf(modelId);
return m && m.name ? m.name : "Hodge-3.5";
}
function modeLabel() {
return shownName();
}
function renderModes() {
$("mode-name").textContent = modeLabel();
const m = modelOf(modelId);
$("mode").title = m ? "Loaded: " + m.name : "Model";
const menu = $("mode-menu");
menu.textContent = "";
const item = (value, title, sub, note, disabled) => {
const b = document.createElement("button");
b.type = "button";
b.setAttribute("role", "menuitemradio");
b.setAttribute("aria-checked", value && mode === value ? "true" : "false");
b.disabled = !!disabled;
const bt = document.createElement("b");
bt.textContent = title;
b.append(bt);
if (sub) {
const sp = document.createElement("span");
sp.textContent = sub;
b.append(sp);
}
if (note) {
const i = document.createElement("i");
i.textContent = note;
b.append(i);
}
b.onclick = () => chooseMode(value);
return b;
};
const filled = ENGINES.map((e) => models.find((y) => y.tier === e.tier)).filter(Boolean);
if (filled.length > 1) {
menu.append(item("auto", "Auto", "Router", "Each message goes to the engine the gate picks, with the tools it needs. Switches carry the continuity chain."));
const axes = document.createElement("div");
axes.className = "mode-axes";
axes.innerHTML = "<span>Small</span><span>Large</span>";
menu.append(axes);
}
if (filled.length) {
const grid = document.createElement("div");
grid.className = "mode-grid";
for (const x of filled) grid.append(item(x.id, x.name, "", x.id === modelId ? "Loaded" : ""));
menu.append(grid);
}
const rest = models.filter((x) => !x.tier);
if (rest.length) {
if (filled.length) menu.append(document.createElement("hr"));
for (const x of rest) menu.append(item(x.id, x.name, "", x.id === modelId ? "Loaded" : ""));
}
$("mode").disabled = generating || compacting || !!swapping || !ready || models.length < 2;
}
function closeModes() {
$("mode-menu").hidden = true;
$("mode").setAttribute("aria-expanded", "false");
}
$("mode").onclick = () => {
const open = $("mode-menu").hidden;
if (open) renderModes();
$("mode-menu").hidden = !open;
$("mode").setAttribute("aria-expanded", open ? "true" : "false");
if (open) {
const c = $("mode-menu").querySelector('[aria-checked="true"]') || $("mode-menu").querySelector("button:not(:disabled)");
if (c) c.focus();
}
};
document.addEventListener("click", (e) => {
if (!$("mode-menu").hidden && !e.target.closest(".mode-pick")) closeModes();
});
$("mode-menu").addEventListener("keydown", (e) => {
if (e.key === "Escape") { closeModes(); $("mode").focus(); }
});
async function chooseMode(value) {
closeModes();
if (!value || value === mode || generating || compacting || swapping) return;
mode = value;
try { localStorage.setItem("champ.mode", mode); } catch { /* this visit only */ }
renderModes();
const m = mode === "auto" ? null : modelOf(mode);
if (m && m.id !== modelId) {
setBusy(true);
await handoff(m, "chosen");
setBusy(false);
}
}
// ---- the context window and the continuity chain
function ctxFull() {
return !!ctxMax && ctxPos > 0.7 * ctxMax;
}
function updateCtx() {
const box = $("ctx");
if (!ctxMax) {
box.hidden = true;
return;
}
box.hidden = false;
const f = Math.min(1, ctxPos / ctxMax);
$("ctx-fill").style.width = Math.round(f * 100) + "%";
$("ctx-text").textContent = ctxPos.toLocaleString() + " / " + ctxMax.toLocaleString();
box.classList.toggle("warn", f > 0.7);
box.title = "Context window: " + ctxPos.toLocaleString() + " of " + ctxMax.toLocaleString() +
" tokens. At 70% " + shownName() + " adds a summary to the continuity chain and starts again from it.";
}
function lastSeq(id) {
const msgs = chats.messages(id);
return msgs.length ? msgs[msgs.length - 1].seq : 0;
}
// One hand-off in the thread: which model took the chat, and that it took the chain with it.
function linkRow(link) {
const p = document.createElement("div");
p.className = "handoff";
p.textContent = (link.from ? link.from + " → " : "→ ") + link.to + " · continuity chain carried";
if (link.reason) p.title = link.reason;
thread.append(p);
}
// Loads another model into a new guest while the page stays: the thread, the chat and the chain are
// untouched, and the next turn primes the new model from the chain (prime -> chats.gather).
let swapping = null;
async function swapModel(m) {
const prevId = modelId;
const prevFlow = flow;
modelId = m.id;
disarmFlow();
status("Loading " + m.name, "busy");
let files;
try {
files = await fromUrl(new URL("/models/" + m.id + "/", location.href).href);
Object.assign(files, await kernels());
} catch (e) {
// Nothing started: the loaded guest keeps running.
modelId = prevId;
flow = prevFlow;
if (flow.on) {
for (const k of FLOW_KERNELS) if (!KERNELS.includes(k)) KERNELS.push(k);
}
paintInstrument();
throw e;
}
await new Promise((resolve, reject) => {
swapping = { resolve, reject, name: m.name };
start(files);
});
primedId = null;
ctxPos = 0;
renderModes();
updateCtx();
}
// A switch is the die's reload beat: route() says reset, so the engine's context is cleared and the
// continuity chain stays. The fence before it: the stretch the old engine holds becomes a segment of
// the chain, so the new engine starts from a summary as well as the recent turns.
async function handoff(m, reason) {
const from = modelOf(modelId);
if (route(ctxFull(), KIND.reload) !== "reset") return false;
if (chatId && primedId === chatId && ready && chats.messages(chatId).some((x) => x.seq >= segFrom && x.role === "assistant")) {
status("Saving context", "busy");
const seg = await hiddenChat(inContextSummaryPrompt(), 160);
if (seg) {
chats.addSegment(chatId, segFrom, lastSeq(chatId), seg);
await mergeRoll(chatId, seg);
}
}
try {
await swapModel(m);
} catch (e) {
notice(shownName() + " could not load " + m.name + ": " + (e && e.message ? e.message : String(e)));
if (!ready && from && from.id !== m.id) {
try { await swapModel(from); } catch { return false; }
}
return false;
}
if (chatId) {
const link = { from: from ? from.name : "", to: m.name, tier: m.tier || "", reason: reason || "" };
chats.add(chatId, { role: "link", text: "", link });
linkRow(link);
toEnd();
}
return true;
}
// On the Space, a model's weights stream from its Hugging Face model repo.
const WEIGHTS = { "hodge-5": "https://huggingface.co/EncryptidSystems/Hodge-5/resolve/main/hodge-5.bnz?download=true" };
const PACKED_URL = "https://huggingface.co/spaces/EncryptidSystems/README/resolve/main/model.bnz?download=true";
const HF_TREE = "https://huggingface.co/api/spaces/EncryptidSystems/README/tree/main";
async function kernels() {
const files = {};
await Promise.all(KERNELS.map(async (k) => {
const r = await fetch(new URL("../kernels/" + k + ".wgsl", here));
if (!r.ok) throw new Error(shownName() + " could not start.");
files["kernels/" + k + ".wgsl"] = new Uint8Array(await r.arrayBuffer());
}));
return files;
}
async function weightProbe(url) {
try {
const res = await fetch(url, { headers: { Range: "bytes=0-15" } });
if (res.status !== 206 && res.status !== 200) return null;
const type = res.headers.get("Content-Type") || "";
if (type.includes("text/html")) return null;
const buf = new Uint8Array(await res.arrayBuffer());
// BNZ2 decodes on the CPU (bnz.js); BNZ4, hodgemix's output, on the GPU (bnz4load.js).
const magic = buf.length >= 4 ? String.fromCharCode(buf[0], buf[1], buf[2], buf[3]) : "";
const codec = magic === "BNZ2" ? "bnz" : magic === "BNZ4" ? "bnz4" : "";
if (!codec) return null;
const cr = res.headers.get("Content-Range") || "";
const total = Number((/\/(\d+)\s*$/.exec(cr) || [])[1]);
const linked = Number(res.headers.get("X-Linked-Size"));
const size = total || linked || (buf.length === Number(res.headers.get("Content-Length")) ? buf.length : 0);
if (!size || size < 32) return null;
return { url: res.url || url, size, codec };
} catch {
return null;
}
}
async function hfWeight() {
try {
const r = await fetch(HF_TREE);
if (!r.ok) return null;
const rows = await r.json();
const file = Array.isArray(rows) ? rows.find((row) => row && row.path === "model.bnz") : null;
const etag = file && file.lfs && file.lfs.oid;
const size = file && file.lfs && Number(file.lfs.size);
if (!etag || !size) return null;
return { etag, size };
} catch {
return null;
}
}
async function fromUrl(base) {
if (!base.endsWith("/")) base += "/";
const files = {};
// The volume, the tokenizer and the weight header are independent. Waiting
// on each in turn was the gap before the guest could compile.
const volP = (async () => {
const vol = await fetch(base + "volume.safetensors");
if (!vol.ok && vol.status !== 404) throw new Error(shownName() + " could not start.");
if (!vol.ok) return null;
return new Uint8Array(await vol.arrayBuffer());
})();
const smallP = Promise.all(SMALL.map(async (f) => {
const r = await fetch(base + f);
if (!r.ok) {
if (f === "config.json" || f === "tokenizer.json") throw new Error(shownName() + " could not start.");
return null;
}
return ["model/" + f, new Uint8Array(await r.arrayBuffer())];
}));
const probedP = weightProbe(WEIGHTS[modelId] || new URL(base + "model.bnz", location.href).href);
const [volBytes, smalls, probed] = await Promise.all([volP, smallP, probedP]);
if (volBytes) {
armFlow();
map.structure(volBytes);
files["model/volume.safetensors"] = volBytes;
}
for (const row of smalls) if (row) files[row[0]] = row[1];
// The folder's own weights first (packed, then plain), then the published copy.
if (probed) {
files["model/model.safetensors"] = { codec: probed.codec, url: probed.url, size: probed.size, room: modelId, etag: "" };
return files;
}
const head = await fetch(base + "model.safetensors", { method: "HEAD" });
const size = Number(head.headers.get("Content-Length"));
if (head.ok && size) {
files["model/model.safetensors"] = { url: base + "model.safetensors", size };
return files;
}
// The published copy is Champ's weights: another model never falls back to them.
if (modelId !== "champ") throw new Error("This model's weights are not on the server.");
const id = await hfWeight();
const published = await weightProbe(PACKED_URL);
if (!published) throw new Error(shownName() + " could not start.");
const etag = id && id.etag && id.size === published.size ? id.etag : "";
files["model/model.safetensors"] = { codec: published.codec, url: published.url, size: published.size, room: "", etag };
return files;
}
const thread = $("thread");
const loading = $("loading");
let assistant = null;
let generating = false;
let ready = false;
let lineBuf = "";
let sawDownload = false;
let shownMax = 0;
function setProgress(p, phase) {
// A fatal guest line already landed. Later download ticks must not paint over it.
const held = statusText.textContent;
if (held === "Stopped" || held === "Session ended" || held === "Unavailable") return;
let shown = p;
if (phase === "download") {
sawDownload = true;
shown = p * 0.72;
} else if (sawDownload) {
shown = 0.72 + p * 0.28;
}
if (shown < shownMax) shown = shownMax;
else shownMax = shown;
const n = Math.max(0, Math.min(100, Math.round(shown * 100)));
$("bar-fill").style.width = n + "%";
if (swapping) {
status("Loading " + swapping.name + " " + n + "%", "busy");
return;
}
$("loading-copy").textContent = "Preparing " + shownName();
status("Preparing", "busy");
}
function showLoading(copy) {
$("loading-copy").textContent = copy;
// A continued chat is already on screen. Keep it there while the model prepares.
if (thread.childElementCount > 0) {
loading.hidden = true;
thread.hidden = false;
return;
}
loading.hidden = false;
thread.hidden = true;
}
function showThread() {
loading.hidden = true;
thread.hidden = false;
}
function bubble(role, text) {
const row = document.createElement("div");
row.className = "msg " + role;
const box = document.createElement("div");
box.className = "bubble";
const who = document.createElement("span");
who.className = "who";
if (role === "user") who.textContent = "You";
else whoLabel(who, undefined);
const body = document.createElement("div");
if (role === "assistant") body.className = "live";
body.textContent = text || "";
box.append(who, body);
row.append(box);
thread.append(row);
thread.parentElement.scrollTop = thread.parentElement.scrollHeight;
return body;
}
// The tool beat on the page: a spinning mark and a short status, never the JSON.
// Rebuilding the mark on every token would restart the spin, so an existing
// loader with the same label and lead stays put.
function showLoad(body, label, lead, beat) {
if (!body) return;
const words = label || "Working…";
const have = body.querySelector(":scope > .load");
const leadEl = body.querySelector(":scope > .lead");
const sameLead = lead ? !!(leadEl && leadEl.textContent === lead) : !leadEl;
if (have && sameLead && have.lastElementChild && have.lastElementChild.textContent === words) {
if (beat) have.dataset.beat = beat;
return;
}
body.replaceChildren();
if (lead) {
const prose = document.createElement("div");
prose.className = "lead";
prose.textContent = lead;
body.append(prose);
}
const row = document.createElement("span");
row.className = "load";
row.setAttribute("role", "status");
if (beat) row.dataset.beat = beat;
const mark = document.createElement("i");
mark.setAttribute("aria-hidden", "true");
const name = document.createElement("span");
name.textContent = words;
row.append(mark, name);
body.append(row);
}
// Words to keep. A loader is not an answer, so its label is left out.
function answerText(body) {
if (!body) return "";
if (body.querySelector(":scope > .load")) {
const lead = body.querySelector(":scope > .lead");
return lead ? lead.textContent.trim() : "";
}
return body.textContent.trim();
}
function notice(text) {
const p = document.createElement("div");
p.className = "notice";
p.textContent = text;
thread.append(p);
showThread();
}
function welcome() {
thread.textContent = "";
const row = document.createElement("div");
row.className = "msg assistant";
row.innerHTML = '<div class="bubble"><span class="who"></span><div>On this device and ready.</div></div>';
row.querySelector(".who").textContent = shownName();
const chips = document.createElement("div");
chips.className = "chips";
for (const t of [
"What can you help me with?",
"Summarize a plan in a few sentences.",
"Draft a short note.",
]) {
const b = document.createElement("button");
b.type = "button";
b.textContent = t;
b.onclick = () => ask(t);
chips.append(b);
}
row.append(chips);
thread.append(row);
}
function setBusy(on) {
generating = on;
$("msg").disabled = !ready || on;
$("send").disabled = !ready || on;
$("think").disabled = !ready || on;
$("plus").disabled = !ready || on;
if (on) closeTools();
$("stop").hidden = !on;
$("newchat").disabled = !ready || on;
$("mode").disabled = on || !!swapping || !ready || models.length < 2;
if (on) closeModes();
if (!on && ready && !swapping && beats.length) {
const [bt, bo] = beats.shift();
setTimeout(() => ask(bt, bo), 0);
}
if (!on && ready) $("msg").focus();
}
function onReady() {
ready = true;
if (swapping) {
const s = swapping;
swapping = null;
status("Ready", "ready");
s.resolve();
return;
}
const back = hashChat();
if (back) {
chatId = back;
showChat(back);
refreshList();
} else welcome();
showThread();
status("Ready", "ready");
setBusy(false);
}
let held = "";
let holding = true;
let rawAnswer = "";
let toolRounds = 0;
let replaceNext = false;
// The bubble is a tool loader, so arriving tokens are not written out as JSON.
let hidingTool = false;
let afterPlain = null;
let lastDone = null;
let thinkOn = false;
// The model on this turn (router.js decide), saved with the answer; null before the first routed turn.
let turnVia = null;
// Chat beats that arrived while busy (router.js accept: stall), at most DEPTH.
const beats = [];
// via undefined: this turn's model; null: an answer saved without one.
function whoLabel(el, via) {
const v = via === undefined ? turnVia : via;
el.textContent = shownName();
if (v && v.reason) el.title = shownName() + " · " + v.reason;
}
let lastAsk = "";
let pendingLearn = "";
function asksClock(text) {
return /\b(date|time|today|tonight|tomorrow|yesterday|weekday|what day|day is it)\b/i.test(text);
}
function finishTurn(ev) {
toolRounds = 0;
replaceNext = false;
hidingTool = false;
rawAnswer = "";
const text = assistant ? answerText(assistant) : "";
if (assistant && !text && assistant.querySelector(".load")) {
const row = assistant.closest(".msg");
if (row) row.remove();
assistant = null;
}
if (assistant && ev) {
const sec = ev.decode_ms > 0 ? (ev.tokens * 1000 / ev.decode_ms) : 0;
const rate = sec ? (Math.round(sec * 10) / 10).toFixed(1) + " tok/s" : "";
const meta = document.createElement("div");
meta.className = "meta";
meta.textContent = [ev.tokens ? ev.tokens + " tokens" : "", rate, ev.reason || ""].filter(Boolean).join(" · ");
assistant.parentElement.append(meta);
}
if (assistant && chatId && assistant.isConnected) {
if (text) {
// jev_join: emit the answer with its model once the result, the chain carried into this engine and
// a place on the page are all there.
const emit = join(true, primedId === chatId, assistant.isConnected) === "emit";
chats.add(chatId, emit && turnVia ? { role: "assistant", text, via: turnVia } : { role: "assistant", text });
showAnswer(assistant, text);
refreshList();
}
}
assistant = null;
stopByte[0] = 0;
nucleusHold = false;
userStop = false;
status("Ready", "ready");
setBusy(false);
if (ctxMax && ctxPos > 0.7 * ctxMax) compact().catch(() => { compacting = false; setBusy(false); });
}
// A finished answer: markdown in place of the streamed text, then its actions.
function showAnswer(body, text) {
body.classList.remove("live");
body.replaceChildren(renderMarkdown(text));
const row = body.closest(".msg");
for (const b of thread.querySelectorAll(".acts-msg .regen")) b.remove();
if (row) {
const bar = messageActions(row, { text, regen: () => regenerate() });
const last = bar.lastChild;
if (last) last.classList.add("regen");
}
}
function userRow(text, seq) {
const body = bubble("user", text);
const row = body.closest(".msg");
messageActions(row, { text, edit: () => startEdit(seq, text) });
return body;
}
function addCard(card, before) {
renderCard(thread, card, before);
if (chatId) chats.add(chatId, { role: "card", text: card.output || "", card });
}
// ---- chats: list, open, edit, regenerate
function setHash(id) {
const want = id ? "#c=" + id : "";
if (location.hash !== want) history.replaceState(null, "", location.pathname + location.search + want);
}
function hashChat() {
const m = /^#c=([\w-]+)$/.exec(location.hash);
return m && chats.meta(m[1]) ? m[1] : null;
}
function refreshList() {
renderChatList($("chats"), chats.list(), chatId, {
open: openChat,
rename: (id, title) => { chats.rename(id, title); refreshList(); },
remove: (id) => {
chats.remove(id);
if (id === chatId) newChat();
else refreshList();
},
refresh: () => refreshList(),
}, $("chat-search").value);
}
const HANDOFF_LABEL = /^[abcdefghjkmnpqrstuvwxyz23456789]{8}$/;
async function resumeHandoff() {
let label = new URLSearchParams(location.search).get("handoff") || "";
const host = location.hostname.toLowerCase();
if (host.endsWith(".encryptid.stream")) {
const lab = host.slice(0, -".encryptid.stream".length);
if (HANDOFF_LABEL.test(lab)) label = lab;
}
if (!HANDOFF_LABEL.test(label)) return;
try {
if (sessionStorage.getItem("champ.handoff") === label && hashChat()) return;
sessionStorage.setItem("champ.handoff", label);
} catch { /* this visit only */ }
let j = null;
try {
const r = await fetch("/api/handoff/" + label, { headers: { Accept: "application/json" }, credentials: "same-origin" });
j = await r.json();
} catch {
return;
}
if (j && j.signin) {
location.href = "/auth/login?return_to=" + encodeURIComponent(location.pathname + location.search);
return;
}
if (!j || !j.ok) {
notice((j && j.output) || "That link has expired.");
return;
}
const id = chats.create(j.title || "Continued");
const lines = String(j.transcript || "").split("\n").filter(Boolean);
let n = 0;
for (const line of lines) {
if (line.startsWith("You: ")) { chats.add(id, { role: "user", text: line.slice(5) }); n++; }
else if (line.startsWith("Hodge-3.5: ")) { chats.add(id, { role: "assistant", text: line.slice("Hodge-3.5: ".length) }); n++; }
else if (line.startsWith("Champ: ")) { chats.add(id, { role: "assistant", text: line.slice(7) }); n++; }
}
if (!n) chats.add(id, { role: "user", text: j.transcript || j.title || "Continue." });
chatId = id;
setHash(id);
showChat(id);
refreshList();
}
function showChat(id) {
thread.textContent = "";
let lastAnswer = null;
for (const m of chats.messages(id)) {
if (m.role === "user") userRow(m.text, m.seq);
else if (m.role === "card" && m.card) renderCard(thread, m.card);
else if (m.role === "link" && m.link) linkRow(m.link);
else if (m.role === "assistant") {
const body = bubble("assistant", "");
whoLabel(body.closest(".msg").querySelector(".who"), m.via || null);
body.classList.remove("live");
body.replaceChildren(renderMarkdown(m.text));
lastAnswer = { body, text: m.text };
messageActions(body.closest(".msg"), { text: m.text });
}
}
if (lastAnswer) showAnswer(lastAnswer.body, lastAnswer.text);
showThread();
toEnd();
}
function openChat(id) {
if (generating || compacting) return;
closeDrawer();
if (id === chatId) return;
chatId = id;
editFrom = null;
pendingLearn = "";
setHash(id);
showChat(id);
refreshList();
}
function newChat() {
if (generating || compacting) return;
closeDrawer();
chatId = null;
editFrom = null;
pendingLearn = "";
resetAllow();
vm.close();
setHash(null);
welcome();
showThread();
refreshList();
}
function startEdit(seq, text) {
if (generating || compacting) return;
editFrom = seq;
$("msg").value = text;
$("msg").dispatchEvent(new Event("input"));
$("msg").focus();
$("msg").placeholder = "Edit your message";
}
function regenerate() {
if (generating || compacting || !chatId) return;
const msgs = chats.messages(chatId);
const lastUser = [...msgs].reverse().find((m) => m.role === "user");
if (!lastUser) return;
ask(lastUser.text, { regen: lastUser.seq });
}
// ---- context: rebuild from the MVCC summaries, and make room when it fills
// Before a model turn: if the model holds another chat (or none), rebuild this
// one from its summaries and recent turns.
async function prime(text, userSeq) {
if (primedId === chatId) return;
await resetModel();
pendingPrefix = chats.gather(chatId, text, userSeq);
primedId = chatId;
segFrom = userSeq;
}
// Runs one model turn whose words go nowhere on the page.
async function hiddenChat(prompt, max, sample, system) {
const hold = assistant;
assistant = document.createElement("div");
const got = await plainChat(prompt, max, sample, system);
assistant = hold;
return (got || "").replace(/\s+/g, " ").trim();
}
async function mergeRoll(id, seg) {
const prev = chats.roll(id);
if (!prev) {
chats.setRoll(id, seg);
return;
}
await resetModel();
const merged = await hiddenChat(rollPrompt(prev, seg), 200);
chats.setRoll(id, merged || prev + " " + seg);
}
// The context is 70% full: Hodge-3.5 summarizes the stretch it holds, that becomes
// a segment and joins the rolling summary, and the next turn starts from those.
async function compact() {
if (compacting || !chatId) return;
compacting = true;
setBusy(true);
status("Saving context", "busy");
const id = chatId;
const msgs = chats.messages(id);
const last = msgs.length ? msgs[msgs.length - 1].seq : 0;
let seg = await hiddenChat(inContextSummaryPrompt(), 160);
if (seg) chats.addSegment(id, segFrom, last, seg);
else seg = await summarizeFromStore(id);
if (seg) await mergeRoll(id, seg);
primedId = null;
ctxPos = 0;
updateCtx();
compacting = false;
status("Ready", "ready");
setBusy(false);
}
// No room left in the model: summarize from the stored turns instead.
async function summarizeFromStore(id) {
const from = chats.covered(id) + 1;
const part = chats.messages(id).filter((m) => m.seq >= from && m.role !== "card");
if (!part.length) return "";
await resetModel();
const seg = await hiddenChat(segmentPrompt(transcript(part, 2400)), 160);
if (seg) chats.addSegment(id, part[0].seq, part[part.length - 1].seq, seg);
return seg;
}
// The guest refused a turn because the context is full: make room, rebuild, resend.
async function recoverFull(cmd) {
compacting = true;
status("Making room", "busy");
const id = chatId;
const msgs = chats.messages(id);
const lastUser = [...msgs].reverse().find((m) => m.role === "user");
const seg = await summarizeFromStore(id);
if (seg) await mergeRoll(id, seg);
await resetModel();
pendingPrefix = chats.gather(id, lastUser ? lastUser.text : "", lastUser ? lastUser.seq : null);
primedId = id;
segFrom = lastUser ? lastUser.seq : 0;
compacting = false;
status("Thinking", "busy");
if (!command(cmd)) {
notice("That message is too long for one turn.");
finishTurn(null);
}
}
// The model sometimes opens with its name. Hold the first tokens and drop
// that label. "Hodge-3.5 is …" stays, because that is an answer.
function takeLead(text, force) {
if (!holding) return text;
held += text;
const name = /^\s*(?:hodge-3\.5|champ)\s*[,:]\s*/i.exec(held);
if (name && (force || held.length > name[0].length)) {
holding = false;
const rest = held.slice(name[0].length);
held = "";
return rest;
}
const unfinished = /^\s*(?:hodge(?:-3(?:\.5)?)?|champ)\s*[,:]?\s*$/i.test(held);
if (!unfinished && (force || held.length > 16 || /^\s*(?!hodge-3\.5\b|champ\b)\S/i.test(held))) {
holding = false;
const rest = held;
held = "";
return rest;
}
return "";
}
// A tool call is a tool beat (router.js KIND.tool). accept() takes it.
// route() is "load" while the context has room — the call streams as the
// loader, then the result joins the engine — and "pass" when the context is
// full, where the result stays on the card. The JSON is not written out.
function paintTool(buf) {
const view = toolStream(buf);
if (view.kind === "text") return false;
// Taken even while the engine is busy. "load" is the spinner and, once the
// call finishes, the result joining the engine. "pass" is the same spinner
// with the result left on the card because the context is full.
const taken = accept(KIND.tool, { busy: generating, loading: !ready || !!swapping, queue: beats.length });
const beat = route(ctxFull(), KIND.tool);
if (taken !== "take") return true;
hidingTool = true;
// A draft the person wants to read is not the notes tool. The spinner stays
// until the words replace it. A picked Notes tool still says Opening notes.
let label = view.tool ? toolStatus(view.tool) : "Working…";
if (view.tool === "notes" && !picks.has("notes") && !wantsSavedNotes(lastAsk)) label = "Writing…";
showLoad(assistant, label, view.lead, beat);
status(label, "busy");
return true;
}
function onToken(ev) {
flowToken = ev.text || "";
if (map) map.token(flowToken);
rawAnswer += ev.text || "";
if (!assistant) {
assistant = bubble("assistant", "");
held = "";
holding = true;
}
if (replaceNext) {
assistant.textContent = "";
held = "";
holding = true;
replaceNext = false;
hidingTool = false;
status("Thinking", "busy");
}
const follow = nearEnd();
if (!afterPlain && paintTool(rawAnswer)) {
if (follow) toEnd();
return;
}
if (hidingTool) {
assistant.textContent = "";
held = "";
holding = true;
hidingTool = false;
const replay = takeLead(rawAnswer, false);
if (replay) assistant.textContent = replay;
if (follow) toEnd();
return;
}
const text = takeLead(ev.text || "", false);
if (text) assistant.textContent += text;
holdNucleus();
if (follow) toEnd();
}
// A second copy of a long span is a loop: drop that copy and stop this sample.
function holdNucleus() {
if (!assistant) return;
const next = nucleusCut(assistant.textContent, 1);
if (next === assistant.textContent) return;
assistant.textContent = next;
nucleusHold = true;
stopByte[0] = 1;
}
function nearEnd() {
const s = thread.parentElement;
return s.scrollHeight - s.scrollTop - s.clientHeight < 80;
}
function toEnd() {
const s = thread.parentElement;
s.scrollTop = s.scrollHeight;
}
function onDone(ev) {
if (ev && ev.ctx) {
ctxPos = Number(ev.pos) || 0;
ctxMax = Number(ev.ctx) || 0;
updateCtx();
}
if (assistant && holding && !hidingTool) {
const text = takeLead("", true);
if (text) assistant.textContent += text;
}
holdNucleus();
if (nucleusHold && !userStop) {
nucleusHold = false;
stopByte[0] = 0;
}
const answered = rawAnswer;
rawAnswer = "";
if (afterPlain) {
const cb = afterPlain;
afterPlain = null;
lastDone = ev;
const visible = assistant ? answerText(assistant) || assistant.textContent.trim() : answered.trim();
cb(visible, ev);
return;
}
if (stopByte[0] !== 0) {
finishTurn(ev);
return;
}
// "Draft a short note" is a note for the chat. The model often answers with
// a notes call. A second turn cannot drop the tool prompt, and deleting the
// loader left the thread empty. Show the words the call already holds.
// A picked Notes tool, or a real save/list, still runs.
if (!picks.has("notes") && !wantsSavedNotes(lastAsk)) {
const words = chatNote(answered, lastAsk);
if (words) {
if (!assistant) assistant = bubble("assistant", "");
hidingTool = false;
assistant.textContent = words;
finishTurn(ev);
return;
}
}
// A writing request is not a canvas call. An unsolicited tool, or a narration
// of one ("the response was: {"id":null}"), is answered again in plain words.
const invented = toolCallOf(answered);
const unwanted = invented && !callAllowed(invented, lastAsk, [...picks]);
if (playedTool(answered) || unwanted) {
const lead = (toolStream(answered).lead || "").trim();
if (unwanted && lead && !playedTool(lead)) {
hidingTool = false;
if (assistant) assistant.textContent = lead;
finishTurn(ev);
return;
}
if (toolRounds > 0) {
hidingTool = false;
if (assistant) assistant.textContent = "I can write that in this chat.";
finishTurn(ev);
return;
}
toolRounds = 1;
hidingTool = true;
if (assistant) showLoad(assistant, "Thinking…", "", "stage");
held = "";
holding = true;
replaceNext = true;
status("Thinking", "busy");
const wire = "The person asked: " + lastAsk + "\nWrite the answer in this chat, in plain words. Do not use a tool. Do not describe a tool.";
if (!command({ op: "chat", text: wire, system: SYSTEM })) {
if (assistant) assistant.textContent = "I can write that in this chat.";
finishTurn(null);
}
return;
}
settleReply(answered, toolRounds, runAgent).then((step) => {
if (step.card) addCard(step.card, assistant ? assistant.closest(".msg") : null);
if (stopByte[0] !== 0) {
finishTurn(null);
return;
}
if (step.action === "finish") {
const visible = assistant ? answerText(assistant) : "";
offerLearn(lastAsk, visible);
finishTurn(ev);
return;
}
if (step.action === "show") {
hidingTool = false;
if (assistant) assistant.textContent = step.text || "";
finishTurn(ev);
return;
}
// In Auto a tool's result is a weight beat: route() loads it into the engine's context, or passes it
// to the page when the context is full; and it is admitted only when it moves the way the question
// does (router.js admit, hodgemix --update's rule). A passed result is the answer as it stands.
if (mode === "auto" && lastAsk) {
const cos = mind.cosine(mind.embed(lastAsk), mind.embed(step.fallback || ""));
if (route(ctxFull(), KIND.tool) === "pass" || !admit(cos)) {
if (step.card && assistant) {
assistant.closest(".msg").remove();
assistant = null;
} else if (assistant) assistant.textContent = step.fallback || "";
finishTurn(ev);
return;
}
}
toolRounds = step.rounds;
hidingTool = true;
if (assistant) showLoad(assistant, step.status, "", route(ctxFull(), KIND.tool));
status(step.status, "busy");
held = "";
holding = true;
replaceNext = true;
if (!command({ op: "chat", text: step.wire, system: SYSTEM })) {
if (assistant) assistant.textContent = step.fallback || "The lookup failed.";
finishTurn(null);
}
}).catch(() => {
hidingTool = false;
if (assistant) assistant.textContent = "The lookup failed.";
finishTurn(null);
});
}
function onEvent(line) {
let ev;
try { ev = JSON.parse(line); } catch { return; }
if (ev.ev === "progress") setProgress(Number(ev.p) || 0, "upload");
else if (ev.ev === "ready") {
if (ev.defaults && Number.isFinite(Number(ev.defaults.temp))) {
sampleDefaults = {
temp: Number(ev.defaults.temp),
top_p: Number(ev.defaults.top_p),
min_p: Number(ev.defaults.min_p),
repeat: Number(ev.defaults.repeat),
};
}
setTowers(ev.towers, ev.vision, ev.audio);
flow.ready(ev.flow);
ctxMax = Number(ev.model && ev.model.ctx) || 0;
ctxPos = 0;
updateCtx();
setFormats(ev.chat_formats, ev.chat_format, ev.rope);
onReady();
}
else if (ev.ev === "format") {
ctxPos = 0;
updateCtx();
if (ev.chat_format && $("format").value !== ev.chat_format) $("format").value = ev.chat_format;
}
else if (ev.ev === "flow") {
try { flow.frame(ev); } catch (e) { console.error(e); notice(e.message); }
}
else if (ev.ev === "token") onToken(ev);
else if (ev.ev === "done") onDone(ev);
else if (ev.ev === "reset" && silentReset) {
const done = silentReset;
silentReset = null;
ctxPos = 0;
updateCtx();
done();
}
else if (ev.ev === "notice" && /context is full/i.test(ev.msg || "") && chatId && !compacting && lastChatCmd) {
recoverFull(lastChatCmd);
}
else if (ev.ev === "reset") {
assistant = null;
rawAnswer = "";
toolRounds = 0;
replaceNext = false;
hidingTool = false;
afterPlain = null;
lastAsk = "";
pendingLearn = "";
welcome();
status("Ready", "ready");
setBusy(false);
}
else if (ev.ev === "notice") {
// A refused turn never sends done: release a summary turn that waits on it.
if (afterPlain) {
const cb = afterPlain;
afterPlain = null;
cb(null);
}
notice(ev.msg || "That message was not run.");
}
else if (ev.ev === "error") {
if (swapping) {
const s = swapping;
swapping = null;
s.reject(new Error(ev.msg || "the model stopped"));
}
status("Stopped", "fail");
notice(ev.msg || shownName() + " stopped.");
setBusy(false);
ready = false;
}
}
function onOut(text) {
lineBuf += text;
let nl;
while ((nl = lineBuf.indexOf("\n")) >= 0) {
const line = lineBuf.slice(0, nl).trim();
lineBuf = lineBuf.slice(nl + 1);
if (line) onEvent(line);
}
}
let worker = null;
function start(files, module) {
if (worker) worker.terminate();
ready = false;
generating = false;
assistant = null;
lineBuf = "";
stopByte[0] = 0;
Atomics.store(i32, 0, 0);
Atomics.store(i32, 1, 0);
if (!swapping) showLoading("Starting " + shownName() + ".");
shownMax = 0;
sawDownload = false;
$("bar-fill").style.width = "0%";
status("Starting", "busy");
$("stop").hidden = true;
$("msg").disabled = true;
$("send").disabled = true;
$("think").disabled = true;
$("plus").disabled = true;
$("newchat").disabled = true;
files.stop = { sab: stopSab, off: 0, size: 1 };
const args = [
"hkruntime.wasm", "-model", "model", "-kernels", "kernels",
"-ui", "-stop", "stop", "-system", SYSTEM,
];
flow.wire(files, args);
worker = new Worker(new URL("champ-worker.js", here), { type: "module" });
worker.onmessage = (e) => {
const m = e.data || {};
if (m.type === "worker-ready") {
worker.postMessage({ type: "boot", module, wasm: WASM_URL, args, files, sab });
status("Starting", "busy");
} else if (m.type === "progress") setProgress(Number(m.p) || 0, "download");
else if (m.type === "out") onOut(m.text || "");
else if (m.type === "err" && m.text && m.text.trim()) {
console.error(m.text);
const line = m.text.trim().split("\n")[0].slice(0, 200);
if (!ready) showLoading(line);
notice(shownName() + " ran into a problem.");
}
else if (m.type === "exit") {
if (swapping) {
const s = swapping;
swapping = null;
s.reject(new Error("the model stopped while loading"));
}
if (lineBuf.trim()) onEvent(lineBuf.trim());
lineBuf = "";
if (statusText.textContent !== "Stopped") status("Session ended", "fail");
ready = false;
setBusy(false);
$("msg").disabled = true;
$("send").disabled = true;
$("think").disabled = true;
$("plus").disabled = true;
}
};
worker.onerror = (e) => {
if (swapping) {
const s = swapping;
swapping = null;
s.reject(new Error(e.message || "the runtime failed to start"));
}
status("Stopped", "fail");
notice(e.message || "The runtime failed to start.");
};
}
async function go(make) {
try {
if (!crossOriginIsolated) throw new Error("Open " + shownName() + " from Encryptid so it can start.");
if (!navigator.gpu) throw new Error("This browser cannot run " + shownName() + ".");
status("Preparing", "busy");
showLoading("Preparing " + shownName() + ".");
const compiling = warmWasm();
const files = await make();
Object.assign(files, await kernels());
start(files, await compiling);
} catch (e) {
status("Unavailable", "fail");
$("loading-copy").textContent = e && e.message ? e.message : String(e);
showLoading($("loading-copy").textContent);
}
}
function plainChat(text, max, sample, system) {
return new Promise((resolve) => {
afterPlain = (visible) => resolve(visible);
held = "";
holding = true;
hidingTool = false;
rawAnswer = "";
const cmd = { op: "chat", text, system: system || SYSTEM, max };
if (sample) cmd.sample = sample;
if (!command(cmd)) {
afterPlain = null;
resolve(null);
}
});
}
function answerParts() {
const row = document.createElement("div");
row.className = "msg assistant";
const box = document.createElement("div");
box.className = "bubble";
const who = document.createElement("span");
who.className = "who";
whoLabel(who, undefined);
const thoughts = document.createElement("div");
thoughts.className = "thoughts";
const body = document.createElement("div");
box.append(who, thoughts, body);
row.append(box);
thread.append(row);
thread.parentElement.scrollTop = thread.parentElement.scrollHeight;
return { thoughts, body };
}
async function deepThink(question) {
const parts = answerParts();
const id = String(mind.head() + 1);
status("Thinking", "busy");
const chain = await runChain(question, {
stop: () => stopByte[0] !== 0,
chat: async (prompt, max) => {
const live = document.createElement("div");
parts.thoughts.append(live);
assistant = live;
const got = await plainChat(prompt, max);
if (got == null) live.remove();
return got;
},
answer: async (prompt, max) => {
assistant = parts.body;
status("Thinking", "busy");
return plainChat(prompt, max);
},
run: (call) => runAgent(call),
notes: (q) => mind.recall(q),
onBegin: async (item) => {
showSpin(parts.thoughts, item.label);
status(item.label || "Working…", "busy");
await paintFrame();
},
onStep: (item) => {
showStep(parts.thoughts, item);
const line = parts.thoughts.lastElementChild ? parts.thoughts.lastElementChild.textContent : "";
mind.commit("think", id + "/" + item.step, line.slice(0, 700));
},
});
assistant = parts.body;
if (chain.stopped || !String(chain.answer || "").trim()) {
if (!chain.trace.length) notice("That message is too long for one turn.");
finishTurn(lastDone);
return;
}
const answer = String(chain.answer).trim();
if (parts.body.textContent.trim() !== answer) parts.body.textContent = answer;
if (!offerLearn(question, answer)) mind.learn(question, answer);
finishTurn(lastDone);
}
function offerLearn(question, said) {
if (!question || !unknownReply(said)) return false;
if (asksClock(question) && !wantsLookup(question) && !wantsTeach(question)) return false;
if (assistant) assistant.textContent = "Would you like me to learn this?";
pendingLearn = question;
return true;
}
async function fromModelTool(t, q, learn) {
assistant = bubble("assistant", "");
const beat = route(ctxFull(), KIND.tool);
if (accept(KIND.tool, { busy: true, loading: !ready || !!swapping, queue: beats.length }) === "take") {
showLoad(assistant, learn ? "Learning…" : "Searching…", "", beat);
}
status(learn ? "Learning…" : "Searching…", "busy");
let ran = { output: "" };
try { ran = await runTool({ tool: "search", args: { q } }); }
catch { ran = { output: "" }; }
if (stopByte[0]) {
finishTurn(null);
return;
}
if (!ran.output || ran.output === "The lookup failed." || ran.output === "Missing search query.") {
assistant.textContent = learn ? shownName() + " could not learn that." : "The lookup failed.";
finishTurn(null);
return;
}
if (learn) {
mind.learn(q, ran.output);
}
let wire = "Results:\n" + ran.output + "\nThe person asked: " + t + "\nAnswer the person in plain words. Do not use JSON.";
const note = learn ? "" : mind.recall(t);
if (note) wire = "Notes:\n" + note + "\n" + wire;
assistant.textContent = "";
held = "";
holding = true;
hidingTool = false;
rawAnswer = "";
status("Thinking", "busy");
if (!command({ op: "chat", text: wire, system: SYSTEM })) {
assistant.textContent = ran.output;
finishTurn(null);
}
}
function paintFrame() {
return new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
}
function showSpin(box, label) {
if (!box) return;
const row = document.createElement("div");
row.className = "load";
row.setAttribute("role", "status");
const mark = document.createElement("i");
mark.setAttribute("aria-hidden", "true");
const name = document.createElement("span");
name.textContent = label || "Working…";
row.append(mark, name);
box.append(row);
const scroller = thread.parentElement;
if (scroller) scroller.scrollTop = scroller.scrollHeight;
}
function clearSpin(box) {
if (!box) return;
for (const el of [...box.querySelectorAll(":scope > .load")]) el.remove();
}
function showStep(box, item) {
if (!box) return;
const line = stepLine(item);
const spinning = box.querySelector(":scope > .load");
if (spinning) {
const done = document.createElement("div");
done.textContent = line;
spinning.replaceWith(done);
return;
}
const row = document.createElement("div");
row.textContent = line;
box.append(row);
}
function stepLine(item) {
if (item.kind === "tool") {
const name = item.label || item.tool;
const flat = String(item.text || "").replace(/\s+/g, " ").trim();
let snippet = flat.slice(0, 180);
if (flat.length > 180) {
const sp = snippet.lastIndexOf(" ");
if (sp > 40) snippet = snippet.slice(0, sp);
}
if (item.kept && (item.tool === "search" || item.page)) {
const hit = String(item.text || "").split("\n")[0].replace(/^\d+\.\s*/, "").trim();
if (item.page) return name;
return hit ? name + " · " + hit.slice(0, 80) : name;
}
if (item.kept) return name + ": " + snippet;
if (item.empty || !snippet) return name + ": nothing returned";
return name + ": set aside " + snippet;
}
return String(item.text || "").replace(/\s+/g, " ").trim().slice(0, 700);
}
async function roomForMore() {
if (!ctxFull() || compacting || !chatId) return;
await compact();
const msgs = chats.messages(chatId);
const lastUser = [...msgs].reverse().find((m) => m.role === "user");
primedId = null;
if (lastUser) await prime(lastUser.text, lastUser.seq);
setBusy(true);
status("Thinking", "busy");
}
async function runDeskPlan(question, plan, learn) {
const parts = answerParts();
status(plan.info ? "Searching…" : "Thinking", "busy");
const asked = asksClock(question) ? ("Current local time: " + clockText() + "\n" + question) : question;
const chain = await runPlan(asked, plan, {
stop: () => stopByte[0] !== 0,
run: async (call) => runAgent(call),
onBegin: async (item) => {
showSpin(parts.thoughts, item.label);
status(item.label || "Working…", "busy");
await paintFrame();
},
room: () => roomForMore(),
keep: (output) => {
if (!sourceKept(output)) return false;
if (frameEcho(output, question)) return false;
const sample = String(output).slice(0, 500);
return admit(mind.cosine(mind.embed(question), mind.embed(sample)));
},
chat: async (prompt, max) => {
const live = document.createElement("div");
parts.thoughts.append(live);
assistant = live;
status("Thinking", "busy");
const got = await plainChat(prompt, max);
if (got == null) live.remove();
return got;
},
answer: async (prompt, max) => {
const scratch = document.createElement("div");
assistant = scratch;
showSpin(parts.thoughts, "Writing…");
status("Writing…", "busy");
await paintFrame();
const got = await plainChat(prompt, max, plan.search ? FACT_SAMPLE : null, plan.system || (plan.route === "recipe" ? RECIPE_SYSTEM : SYSTEM));
clearSpin(parts.thoughts);
if (got == null) return null;
return (scratch.textContent || "").trim() || String(got || "").trim();
},
commit: (piece) => {
if (!chatId || !piece) return;
const prev = chats.draft(chatId) || "";
const next = prev ? prev.replace(/\s+$/, "") + "\n\n" + piece : piece;
chats.setDraft(chatId, next);
parts.body.textContent = chats.draft(chatId) || "";
},
card: (card) => addCard(card, parts.body.closest(".msg")),
onStep: (item) => { showStep(parts.thoughts, item); },
});
const ready = () => (chatId && chats.draft(chatId)) || "";
const drew = (chain.trace || []).some((x) => x.kind === "tool" && x.tool === "canvas" && x.kept);
if (drew) {
assistant = parts.body;
finishTurn(lastDone);
if (chatId) chats.clearDraft(chatId);
return;
}
if (chain.stopped || (!ready() && !String(chain.answer || "").trim())) {
if (!chain.trace.length) notice("That message is too long for one turn.");
const partial = ready();
if (partial) parts.body.textContent = partial;
assistant = parts.body;
finishTurn(lastDone);
if (chatId) chats.clearDraft(chatId);
return;
}
if (chatId && !ready()) chats.setDraft(chatId, String(chain.answer).trim());
const answer = ready() || String(chain.answer).trim();
parts.body.textContent = answer;
assistant = parts.body;
if (learn) mind.learn(question, answer);
else if (!offerLearn(question, answer)) mind.learn(question, answer);
finishTurn(lastDone);
if (chatId) chats.clearDraft(chatId);
}
// opts.from: an edited message replaces seq `from` and everything after it.
// opts.regen: answer the user message at that seq again.
async function ask(text, opts) {
const o = opts || {};
const t = text.trim();
if (!t) return;
if (accept(KIND.chat, { busy: generating || compacting, loading: !ready || !!swapping, queue: beats.length }) === "stall") {
if (ready && beats.length < DEPTH) beats.push([text, opts]);
return;
}
if (!chatId) {
chatId = chats.create(t);
setHash(chatId);
if (thread.querySelector(".chips")) thread.textContent = "";
}
let userSeq;
if (o.regen != null) {
chats.truncate(chatId, o.regen + 1);
primedId = null;
userSeq = o.regen;
showChat(chatId);
} else {
if (o.from != null) {
chats.truncate(chatId, o.from);
primedId = null;
showChat(chatId);
}
userSeq = chats.add(chatId, { role: "user", text: t });
const body = userRow(t, userSeq);
if (pendingMedia.length) {
const note = document.createElement("div");
note.className = "media-note";
note.textContent = pendingMedia.map(mediaLabel).join(" · ");
body.prepend(note);
}
}
noteUrls(t);
refreshList();
toEnd();
stopByte[0] = 0;
toolRounds = 0;
replaceNext = false;
hidingTool = false;
status("Thinking", "busy");
setBusy(true);
// /run, /notes, /note, /task, /tasks, /done, /canvas: the tool runs as typed.
const direct = slashCall(text);
if (direct) {
pendingLearn = "";
status(toolStatus(direct.tool).replace("…", ""), "busy");
let ran;
try { ran = await runAgent(direct); } catch { ran = { output: "The tool failed.", exit_code: 1 }; }
addCard({ tool: direct.tool, args: direct.args, output: ran.output, exit_code: ran.exit_code, data: ran.data || null });
finishTurn(null);
return;
}
// The router (router.js): the gate picks this message's engine and the tools it needs. A different
// model than the loaded one is a hand-off that carries the continuity chain.
const d = decide({ text: t, mode, models, loaded: modelId, think: thinkOn, picks: [...picks] });
if (d.model && d.swap && !(await handoff(d.model, d.reason))) d.think = thinkOn;
const on = modelOf(modelId);
turnVia = on ? { id: on.id, name: on.name, tier: on.tier || "", label: engineOf(on) && mode === "auto" ? engineOf(on).label : on.name, reason: on.id === (d.model && d.model.id) ? d.reason : "" } : null;
status("Thinking", "busy");
if (pendingLearn && acceptsLearn(t)) {
const q = pendingLearn;
pendingLearn = "";
lastAsk = q;
await fromModelTool(q, q, true);
return;
}
if (pendingLearn && declinesLearn(t)) {
pendingLearn = "";
assistant = bubble("assistant", "Okay.");
finishTurn(null);
return;
}
pendingLearn = "";
lastAsk = t;
const chosen = d.tools;
// The model names the route. The guest applies a system prompt only on a
// fresh chat, so the think pass has to start from a reset. Continuing the
// last answer drops THINK_SYSTEM and the pass starts the reply. A named
// word stands. A pass that never names one still looks up a checkable
// question, and a recipe stays with the model. Prime rebuilds the chat after.
let routeName = "talk";
if (!pendingMedia.length) {
await resetModel();
primedId = null;
pendingPrefix = "";
const thought = await hiddenChat(t, 16, { temp: 0, top_p: 1, min_p: 0, repeat: 1 }, THINK_SYSTEM);
if (named(thought)) routeName = routeOf(thought);
else if (factWhenUnnamed(t, thought)) routeName = "fact";
// The think pass stops at 16 tokens. That cap is not the answer's length.
lastDone = null;
primedId = null;
}
await prime(t, userSeq);
const plan = planOf(t, { think: thinkOn || d.think, picks: [...picks], route: routeName });
// A message with an image or a clip is answered from those tokens, not from tools.
if (!pendingMedia.length && !(plan.plain && plan.steps.length === 1)) {
try {
await runDeskPlan(t, plan, wantsTeach(t));
} catch {
notice(shownName() + " ran into a problem.");
finishTurn(null);
}
return;
}
assistant = bubble("assistant", "");
held = "";
holding = true;
rawAnswer = "";
let wire = asksClock(t) ? ("Current local time: " + clockText() + "\n" + t) : t;
const hint = pickedHint(chosen);
if (hint) wire = hint + "\n" + wire;
const note = mind.recall(t);
if (note) wire = "Notes:\n" + note + "\n" + wire;
const cmd = { op: "chat", text: wire, system: plan.system || SYSTEM };
if (pendingMedia.length) {
cmd.media = pendingMedia.map((m) => m.image
? { kind: "image", rows: m.rows, cols: m.cols, rgb: m.rgb }
: m.mel
? { kind: "mel", frames: m.frames, bins: m.bins, feat: m.feat }
: { kind: m.kind, n: m.n, feat: m.feat, phi: m.phi });
pendingMedia = [];
}
if (!command(cmd)) {
notice("That message is too long for one turn.");
setBusy(false);
}
}
$("newchat").onclick = () => newChat();
$("chat-search").addEventListener("input", () => refreshList());
function closeDrawer() {
$("side").classList.remove("open");
$("scrim").hidden = true;
$("menu").setAttribute("aria-expanded", "false");
}
$("menu").onclick = () => {
const open = !$("side").classList.contains("open");
$("side").classList.toggle("open", open);
$("scrim").hidden = !open;
$("menu").setAttribute("aria-expanded", open ? "true" : "false");
};
$("scrim").onclick = closeDrawer;
thread.parentElement.addEventListener("scroll", () => { $("to-end").hidden = nearEnd() || thread.hidden; });
$("to-end").onclick = () => { toEnd(); $("to-end").hidden = true; };
document.addEventListener("keydown", (e) => {
if (e.key === "Escape" && editFrom != null) {
editFrom = null;
$("msg").value = "";
$("msg").placeholder = "Message " + shownName();
}
});
refreshList();
$("stop").onclick = () => { userStop = true; stopByte[0] = 1; status("Stopping", "busy"); };
$("think").onclick = () => {
thinkOn = !thinkOn;
$("think").setAttribute("aria-pressed", thinkOn ? "true" : "false");
};
// + : tools the person picks stay chosen for the next messages until removed.
const picks = new Set();
function closeTools() {
$("tool-menu").hidden = true;
$("plus").setAttribute("aria-expanded", "false");
}
function renderPicks() {
for (const b of $("tool-menu").children) {
if (b.dataset.tool) b.setAttribute("aria-checked", picks.has(b.dataset.tool) ? "true" : "false");
}
const box = $("picked");
box.textContent = "";
for (const p of PICKS) {
if (!picks.has(p.tool)) continue;
const chip = document.createElement("button");
chip.type = "button";
chip.textContent = p.label + " ×";
chip.setAttribute("aria-label", "Stop using " + p.label);
chip.onclick = () => { picks.delete(p.tool); renderPicks(); $("msg").focus(); };
box.append(chip);
}
box.hidden = !picks.size;
}
for (const p of PICKS) {
const b = document.createElement("button");
b.type = "button";
b.setAttribute("role", "menuitemcheckbox");
b.dataset.tool = p.tool;
b.textContent = p.label;
b.onclick = () => {
if (picks.has(p.tool)) picks.delete(p.tool);
else picks.add(p.tool);
renderPicks();
};
$("tool-menu").append(b);
}
renderPicks();
// + Image or audio: the L-A towers (tower.wasm, hodgemix tower) turn an image into 196
// patch tokens and a clip into 50 tokens a second. The guest projects them into the
// residual stream at the start of the next message. It says it has the embedding layers
// in its ready event ("towers").
const AUDIO_MAX_S = 30;
let towersOn = false;
// The guest has the assimilated vision encoder (model/encoder.go): an image goes to it as a
// grid of 16-pixel patches instead of through the L-A tower.
let visionOn = false;
// ...and the assimilated audio encoder (model/audio.go): a clip goes to it as log-mel frames.
let audioOn = false;
const PATCH = 16, POOL = 3, MAX_PATCHES = 2520;
let towerApi = null;
let attached = []; // {kind, name, n, feat, phi}: at most one image and one clip
let pendingMedia = [];
async function towerReady() {
if (towerApi) return towerApi;
if (!globalThis.Go) {
await new Promise((resolve, reject) => {
const s = document.createElement("script");
s.src = new URL("wasm_exec.js", here).href;
s.onload = resolve;
s.onerror = () => reject(new Error("The towers could not load."));
document.head.append(s);
});
}
const go = new globalThis.Go();
const { instance } = await WebAssembly.instantiateStreaming(fetch(new URL("tower.wasm", here)), go.importObject);
go.run(instance);
towerApi = globalThis.hodgeTower;
if (!towerApi || !towerApi.ready) throw new Error("The towers could not start.");
return towerApi;
}
function b64(u8) {
let s = "";
for (let i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000));
return btoa(s);
}
// The tower resizes to 224 x 224 itself; drawing at that size first keeps the copy small.
async function imageRGB(file) {
const bmp = await createImageBitmap(file);
const c = new OffscreenCanvas(224, 224);
const g = c.getContext("2d");
g.drawImage(bmp, 0, 0, 224, 224);
bmp.close();
const px = g.getImageData(0, 0, 224, 224).data;
const rgb = new Float32Array(224 * 224 * 3);
for (let i = 0; i < 224 * 224; i++) {
rgb[3 * i] = px[4 * i] / 255;
rgb[3 * i + 1] = px[4 * i + 1] / 255;
rgb[3 * i + 2] = px[4 * i + 2] / 255;
}
return rgb;
}
// Mono 16 kHz: an offline context at that rate decodes and resamples; channels are averaged.
async function audioPCM(file) {
const a = await new OfflineAudioContext(1, 1, 16000).decodeAudioData(await file.arrayBuffer());
const n = Math.min(a.length, 16000 * AUDIO_MAX_S);
const pcm = new Float32Array(n);
for (let ch = 0; ch < a.numberOfChannels; ch++) {
const d = a.getChannelData(ch);
for (let i = 0; i < n; i++) pcm[i] += d[i] / a.numberOfChannels;
}
return { pcm, cut: a.length > n, secs: n / 16000 };
}
// The patch grid for a w x h image: aspect kept, sides multiples of the 3 x 3 pool, at most
// MAX_PATCHES patches, never enlarged past the image except up to one pool block.
function patchGrid(w, h) {
const s = Math.min(1, Math.sqrt(MAX_PATCHES * PATCH * PATCH / (w * h)));
let cols = Math.max(POOL, Math.floor(w * s / (PATCH * POOL)) * POOL);
let rows = Math.max(POOL, Math.floor(h * s / (PATCH * POOL)) * POOL);
while (rows * cols > MAX_PATCHES) {
if (cols >= rows) cols -= POOL;
else rows -= POOL;
}
return { rows, cols };
}
async function imagePatches(file) {
const bmp = await createImageBitmap(file);
const { rows, cols } = patchGrid(bmp.width, bmp.height);
const W = cols * PATCH, H = rows * PATCH;
const c = new OffscreenCanvas(W, H);
const g = c.getContext("2d");
g.drawImage(bmp, 0, 0, W, H);
bmp.close();
const px = g.getImageData(0, 0, W, H).data;
const rgb = new Uint8Array(W * H * 3);
for (let i = 0; i < W * H; i++) {
rgb[3 * i] = px[4 * i];
rgb[3 * i + 1] = px[4 * i + 1];
rgb[3 * i + 2] = px[4 * i + 2];
}
return { rows, cols, rgb };
}
async function attach(file) {
const kind = file.type.startsWith("image/") ? "vision" : file.type.startsWith("audio/") ? "audio" : "";
if (!kind) {
notice("Attach an image or an audio file.");
return;
}
status(kind === "vision" ? "Reading the image" : "Listening", "busy");
try {
if (kind === "vision" && visionOn) {
const im = await imagePatches(file);
attached = attached.filter((m) => m.kind !== kind);
attached.push({ kind, image: true, name: file.name, rows: im.rows, cols: im.cols, rgb: b64(im.rgb) });
renderAttached();
status(ready ? "Ready" : "Preparing", ready ? "ready" : "busy");
return;
}
const api = await towerReady();
let r;
let label = file.name;
if (kind === "vision") {
const rgb = await imageRGB(file);
r = api.vision(new Uint8Array(rgb.buffer), 224, 224);
} else {
const a = await audioPCM(file);
label += " (" + Math.round(a.secs) + " s" + (a.cut ? ", first " + AUDIO_MAX_S + " s" : "") + ")";
if (audioOn) {
const mel = api.mel(new Uint8Array(a.pcm.buffer));
if (mel.error) throw new Error(mel.error);
attached = attached.filter((m) => m.kind !== kind);
attached.push({ kind, mel: true, name: label, frames: mel.frames, bins: mel.bins, feat: b64(mel.feat) });
renderAttached();
status(ready ? "Ready" : "Preparing", ready ? "ready" : "busy");
return;
}
r = api.audio(new Uint8Array(a.pcm.buffer));
}
if (r.error) throw new Error(r.error);
attached = attached.filter((m) => m.kind !== kind);
attached.push({ kind, name: label, n: r.n, feat: b64(r.feat), phi: b64(r.phi) });
renderAttached();
} catch (e) {
notice((e && e.message) || "That file could not be read.");
}
status(ready ? "Ready" : "Preparing", ready ? "ready" : "busy");
}
function mediaLabel(m) {
return (m.kind === "vision" ? "Image: " : "Audio: ") + m.name;
}
function renderAttached() {
const box = $("attached");
box.textContent = "";
for (const m of attached) {
const chip = document.createElement("button");
chip.type = "button";
chip.textContent = mediaLabel(m) + " ×";
chip.setAttribute("aria-label", "Remove " + mediaLabel(m));
chip.onclick = () => { attached = attached.filter((x) => x !== m); renderAttached(); $("msg").focus(); };
box.append(chip);
}
box.hidden = !attached.length;
}
const mediaItem = document.createElement("button");
mediaItem.type = "button";
mediaItem.setAttribute("role", "menuitem");
mediaItem.textContent = "Image or audio…";
mediaItem.hidden = true;
mediaItem.onclick = () => { closeTools(); $("media-file").click(); };
$("tool-menu").append(mediaItem);
$("media-file").onchange = () => {
const f = $("media-file").files[0];
$("media-file").value = "";
if (f) attach(f);
};
function setTowers(on, vision, audio) {
visionOn = !!vision;
audioOn = !!audio;
towersOn = !!on || visionOn || audioOn;
mediaItem.hidden = !towersOn;
if (!towersOn && attached.length) { attached = []; renderAttached(); }
}
$("plus").onclick = () => {
const open = $("tool-menu").hidden;
$("tool-menu").hidden = !open;
$("plus").setAttribute("aria-expanded", open ? "true" : "false");
if (open) $("tool-menu").firstElementChild.focus();
};
document.addEventListener("click", (e) => {
if (!$("tool-menu").hidden && !e.target.closest(".tool-pick")) closeTools();
});
$("tool-menu").addEventListener("keydown", (e) => {
if (e.key === "Escape") { closeTools(); $("plus").focus(); }
});
$("chat").onsubmit = (e) => {
e.preventDefault();
let t = $("msg").value;
if ((!t.trim() && !attached.length) || !ready || generating || compacting) return;
pendingMedia = attached;
attached = [];
renderAttached();
if (!t.trim()) t = pendingMedia.some((m) => m.kind === "vision") ? "What is in this image?" : "What is in this audio?";
$("msg").value = "";
$("msg").style.height = "auto";
$("msg").placeholder = "Message " + shownName();
const from = editFrom;
editFrom = null;
ask(t, from != null ? { from } : undefined);
};
$("msg").addEventListener("input", () => {
$("msg").style.height = "auto";
$("msg").style.height = Math.min(160, $("msg").scrollHeight) + "px";
});
$("msg").addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
$("chat").requestSubmit();
}
});
const AGENT_KEY = "champ.agent";
function agentAccepted() {
try { return !!(storage && storage.getItem(AGENT_KEY) === "1"); } catch { return false; }
}
function beginDesk() {
if ("serviceWorker" in navigator) navigator.serviceWorker.register("sw.js");
resumeHandoff();
go(async () => fromUrl(await pickModel()));
}
$("agent-terms").addEventListener("cancel", (e) => e.preventDefault());
$("agent-accept").onclick = () => {
try { if (storage) storage.setItem(AGENT_KEY, "1"); } catch { /* this visit only */ }
$("agent-terms").close();
beginDesk();
};
$("agent-deny").onclick = () => {
$("agent-choice").hidden = true;
$("agent-declined").hidden = false;
status("Stopped", "fail");
};
warmWasm().catch(() => {});
if (agentAccepted()) beginDesk();
else {
status("Terms", "");
$("agent-terms").showModal();
}
</script>
</body>
</html>
|