Spaces:
Running
Running
File size: 93,512 Bytes
8bbf912 2204706 8bbf912 |
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 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inverse Turing Test - AI Edition</title>
<!-- Include Marked.js library for Markdown rendering -->
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<!-- Include Axios for other API providers -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<!-- Google AI SDK -->
<script type="module">
// Dynamically imported later if Gemini provider is selected
</script>
<style>
/* --- CSS Variables for Theming (Refined) --- */
:root {
--font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
--border-radius: 8px; /* Slightly larger radius */
--transition-speed: 0.25s;
--branding-bar-height: 45px; /* Height of the new top branding bar */
/* Light Mode (Default) */
--bg-primary: #f4f7f9; /* Main background - slightly cooler */
--bg-secondary: #ffffff; /* Card/container background */
--bg-tertiary: #eef2f5; /* Input/subtle background - cooler */
--text-primary: #2a3342; /* Main text - softer black */
--text-secondary: #5a6a85; /* Lighter text - softer grey */
--text-accent: #0062cc; /* Links, highlights - adjusted blue */
--border-color: #d8e0e8; /* Borders - softer */
--shadow-color: rgba(42, 51, 66, 0.08); /* Softer shadow */
--primary-button-bg: #007bff;
--primary-button-hover-bg: #0069d9;
--primary-button-text: #ffffff;
--human-accent: #28a745; /* Green */
--human-bg: #eaf6ec; /* Lighter green bg */
--ai-accent: #17a2b8; /* Cyan/Teal */
--ai-bg: #e8f6f8; /* Lighter cyan bg */
--system-accent: #6c757d; /* Grey */
--system-bg: #f8f9fa; /* Very light grey bg */
--error-accent: #dc3545; /* Red */
--error-bg: #f8d7da;
--vote-accent: #ffc107; /* Yellow */
--vote-bg: #fff9e6; /* Lighter yellow bg */
--input-bg: #ffffff;
--input-border: #ced4da;
--code-bg: #eef2f5; /* Match tertiary */
--reasoning-bg: rgba(0, 0, 0, 0.02); /* Subtle reasoning bg */
--reasoning-border: rgba(0, 0, 0, 0.05);
}
html.dark-mode {
/* Dark Mode (Refined) */
--bg-primary: #1f232a; /* Dark grey/blue base */
--bg-secondary: #2a303a; /* Slightly lighter dark */
--bg-tertiary: #353c4a; /* Even lighter dark */
--text-primary: #e1e8f0; /* Light grey/white */
--text-secondary: #9da9bb; /* Lighter grey */
--text-accent: #6cb2f0; /* Lighter blue */
--border-color: #404855; /* Darker border */
--shadow-color: rgba(0, 0, 0, 0.2); /* Darker shadow */
--primary-button-bg: #0d6efd;
--primary-button-hover-bg: #3b82f6;
--primary-button-text: #ffffff;
--human-accent: #34c759; /* Brighter Green */
--human-bg: #2a3a32; /* Dark Greenish */
--ai-accent: #64d2ff; /* Brighter Cyan */
--ai-bg: #283a40; /* Dark Cyanish */
--system-accent: #9da9bb; /* Grey */
--system-bg: #353c4a; /* Match tertiary */
--error-accent: #f77a8f; /* Brighter Red */
--error-bg: #4d2a2f; /* Dark Reddish */
--vote-accent: #ffd65a; /* Brighter Yellow */
--vote-bg: #4d3f28; /* Dark Yellowish */
--input-bg: #353c4a; /* Match tertiary */
--input-border: #505866;
--code-bg: #303642; /* Darker code bg */
--reasoning-bg: rgba(255, 255, 255, 0.04); /* Subtle reasoning bg */
--reasoning-border: rgba(255, 255, 255, 0.08);
}
/* --- Base Styles --- */
*, *::before, *::after { box-sizing: border-box; }
body {
font-family: var(--font-family);
background-color: var(--bg-primary);
color: var(--text-primary);
margin: 0;
padding: var(--branding-bar-height) 20px 20px 20px; /* Adjusted top padding for branding bar */
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
font-size: 16px;
line-height: 1.6;
transition: background-color var(--transition-speed) ease, color var(--transition-speed) ease;
box-sizing: border-box;
}
/* --- Branding Bar --- */
.branding-bar {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: var(--branding-bar-height);
background-color: var(--bg-secondary);
border-bottom: 1px solid var(--border-color);
display: flex;
justify-content: center;
align-items: center;
z-index: 1001; /* Above modals (1000) */
padding: 0 20px; /* Horizontal padding for content within the bar */
box-sizing: border-box;
transition: background-color var(--transition-speed) ease, border-color var(--transition-speed) ease;
}
.branding-bar a,
.branding-bar span.separator {
font-family: var(--font-family);
color: var(--text-secondary);
text-decoration: none;
font-size: 0.9em;
margin: 0 10px; /* Spacing for links and separators */
transition: color var(--transition-speed) ease;
}
.branding-bar a:hover {
color: var(--text-accent);
text-decoration: underline;
}
.branding-bar span.separator {
user-select: none; /* Make separator non-selectable */
color: var(--border-color); /* Separator color to match border */
}
#app-container {
background-color: var(--bg-secondary);
border-radius: var(--border-radius);
box-shadow: 0 8px 25px var(--shadow-color);
width: 100%;
max-width: 900px;
height: calc(100vh - var(--branding-bar-height) - 40px); /* Adjusted height */
max-height: 800px;
display: flex;
flex-direction: column;
overflow: hidden;
border: 1px solid var(--border-color);
transition: background-color var(--transition-speed) ease, border-color var(--transition-speed) ease, box-shadow var(--transition-speed) ease;
}
button {
font-family: var(--font-family);
border-radius: var(--border-radius);
padding: 10px 20px;
font-size: 1em;
cursor: pointer;
border: none;
transition: background-color 0.2s ease, transform 0.1s ease, box-shadow 0.2s ease;
font-weight: 600;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
button:hover {
filter: brightness(105%);
box-shadow: 0 4px 8px rgba(0,0,0,0.07);
}
button:active {
transform: translateY(1px);
box-shadow: 0 1px 2px rgba(0,0,0,0.05);
filter: brightness(100%);
}
button:disabled {
opacity: 0.6;
cursor: not-allowed;
filter: none;
box-shadow: none;
}
/* Consolidated input styling */
input[type="text"],
input[type="password"],
input[type="number"],
select,
textarea {
font-family: var(--font-family);
width: 100%;
padding: 12px 15px;
border: 1px solid var(--input-border);
border-radius: var(--border-radius);
margin-bottom: 15px;
font-size: 1em;
background-color: var(--input-bg); /* Apply theme background */
color: var(--text-primary); /* Apply theme text color */
transition: background-color var(--transition-speed) ease, color var(--transition-speed) ease, border-color var(--transition-speed) ease, box-shadow var(--transition-speed) ease;
box-shadow: inset 0 1px 3px rgba(0,0,0,0.04);
appearance: none; /* Remove default system appearance for select */
}
/* Specific style for select dropdown arrow */
select {
background-image: linear-gradient(45deg, transparent 50%, var(--text-secondary) 50%), linear-gradient(135deg, var(--text-secondary) 50%, transparent 50%);
background-position: calc(100% - 20px) calc(1em + 2px), calc(100% - 15px) calc(1em + 2px);
background-size: 5px 5px, 5px 5px;
background-repeat: no-repeat;
padding-right: 40px; /* Make space for the custom arrow */
}
/* Hover/Focus styling for all inputs */
input:focus, select:focus, textarea:focus {
outline: none;
border-color: var(--primary-button-bg);
box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.15), inset 0 1px 3px rgba(0,0,0,0.04);
}
textarea {
line-height: 1.5;
resize: vertical; /* Allow textarea resize */
}
/* Fix for select in dark mode needing explicit color scheme hint */
html.dark-mode select {
color-scheme: dark;
}
/* --- Modal Styles (Improved) --- */
.modal-overlay {
position: fixed;
top: var(--branding-bar-height); /* Start below the branding bar */
left: 0;
width: 100%;
height: calc(100vh - var(--branding-bar-height)); /* Fill remaining height */
background-color: rgba(0, 0, 0, 0.6);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
padding: 20px;
backdrop-filter: blur(4px);
opacity: 0;
visibility: hidden;
transition: opacity 0.3s ease, visibility 0.3s ease;
box-sizing: border-box;
}
.modal-overlay:not(.hidden) {
opacity: 1;
visibility: visible;
}
.modal-content {
background-color: var(--bg-secondary);
color: var(--text-primary);
padding: 35px 40px;
border-radius: var(--border-radius);
max-width: 750px;
width: 95%;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
text-align: left;
max-height: calc(90vh - var(--branding-bar-height)); /* Adjust max-height considering the branding bar */
overflow-y: auto;
transition: background-color var(--transition-speed) ease, color var(--transition-speed) ease, transform 0.3s ease;
transform: scale(0.95);
position: relative; /* Added for positioning theme toggle button */
}
.modal-overlay:not(.hidden) .modal-content {
transform: scale(1);
}
.modal-content h2 {
margin-top: 0;
margin-bottom: 15px;
color: var(--text-primary);
text-align: center;
font-weight: 600;
font-size: 1.6em;
}
.modal-content h4 {
margin-top: 25px;
margin-bottom: 10px;
color: var(--text-accent);
font-weight: 600;
border-bottom: 1px solid var(--border-color);
padding-bottom: 8px;
transition: border-color var(--transition-speed) ease;
}
.modal-content p, .modal-content ul {
margin-bottom: 20px;
line-height: 1.7;
}
.modal-content ul {
padding-left: 25px;
}
.modal-content li {
margin-bottom: 12px;
}
.modal-content .intro-paragraph {
background-color: var(--bg-tertiary);
padding: 15px 20px;
border-radius: var(--border-radius);
margin-bottom: 25px;
font-size: 1.05em;
border-left: 4px solid var(--text-accent);
transition: background-color var(--transition-speed) ease, border-color var(--transition-speed) ease;
}
.modal-content label {
display: block;
margin-bottom: 8px;
font-weight: 600;
color: var(--text-secondary);
font-size: 0.95em;
}
.modal-content a {
color: var(--text-accent);
text-decoration: none;
font-weight: 500;
}
.modal-content a:hover {
text-decoration: underline;
filter: brightness(110%);
}
.modal-content button#startGameBtn,
.modal-content button#restartGameBtn {
background-color: var(--primary-button-bg);
color: var(--primary-button-text);
width: 100%;
padding: 14px 20px;
font-size: 1.1em;
margin-top: 25px;
}
.modal-content button#startGameBtn:hover,
.modal-content button#restartGameBtn:hover {
background-color: var(--primary-button-hover-bg);
}
/* Specific styling for Game Over Modal buttons if needed */
#gameOverModal .modal-content button {
width: auto; /* Allow buttons to size naturally */
padding: 12px 25px;
}
#gameOverModal .modal-content button#closeGameOverModalBtn { /* Custom style for new button */
background-color: var(--system-accent);
color: var(--primary-button-text); /* Assuming white text is good on system-accent */
margin-right: 15px; /* Space between buttons */
}
#gameOverModal .modal-content button#closeGameOverModalBtn:hover {
filter: brightness(110%); /* Generic hover for system button */
}
.api-warning-footer {
background-color: var(--bg-tertiary);
color: var(--text-secondary);
border: 1px solid var(--border-color);
padding: 12px 15px;
border-radius: var(--border-radius);
font-size: 0.9em;
margin-top: 20px;
text-align: center;
border-left: 3px solid var(--vote-accent);
transition: background-color var(--transition-speed) ease, color var(--transition-speed) ease, border-color var(--transition-speed) ease;
}
.api-warning-footer strong {
font-weight: 600;
}
.config-group {
margin-bottom: 25px;
padding: 20px;
border: 1px solid var(--border-color);
border-radius: var(--border-radius);
background-color: var(--bg-tertiary);
transition: background-color var(--transition-speed) ease, border-color var(--transition-speed) ease;
}
.config-group h4 {
margin-top: 0;
margin-bottom: 15px;
border: none;
padding-bottom: 0;
color: var(--text-primary);
}
.config-group.hidden { display: none; }
.hyperparam-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 15px;
margin-top: 10px;
}
/* --- Game Area Styles (Improved) --- */
#game-area {
display: flex;
flex-direction: column;
height: 100%;
padding: 0;
position: relative;
}
#theme-toggle-button {
position: absolute;
top: 12px;
right: 15px;
background: var(--bg-tertiary);
border: 1px solid var(--border-color);
color: var(--text-secondary);
font-size: 1.3em;
cursor: pointer;
padding: 5px 9px;
border-radius: 50%;
line-height: 1;
width: 36px;
height: 36px;
display: flex;
align-items: center;
justify-content: center;
z-index: 10;
transition: color var(--transition-speed) ease, border-color var(--transition-speed) ease, background-color var(--transition-speed) ease, transform 0.2s ease;
}
#theme-toggle-button:hover {
color: var(--text-primary);
border-color: var(--text-secondary);
background-color: var(--bg-secondary);
transform: scale(1.05);
}
#status-area {
padding: 12px 20px;
border-bottom: 1px solid var(--border-color);
margin-bottom: 0;
background-color: var(--bg-secondary);
border-radius: 0;
font-size: 0.9em;
display: flex;
justify-content: flex-start;
align-items: center;
flex-wrap: wrap;
gap: 18px;
color: var(--text-secondary);
font-weight: 500;
transition: background-color var(--transition-speed) ease, border-color var(--transition-speed) ease, color var(--transition-speed) ease;
}
#status-area span {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 4px 10px;
border-radius: calc(var(--border-radius) / 2);
white-space: nowrap;
background-color: var(--bg-tertiary);
transition: background-color var(--transition-speed) ease;
}
#status-area .role-human {
background-color: var(--human-accent);
color: var(--primary-button-text);
font-weight: bold;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
#status-area .role-ai { /* Optional styling */ }
#status-area #provider-info {
background-color: var(--system-accent);
color: var(--primary-button-text);
font-weight: bold;
}
#game-log {
flex-grow: 1;
overflow-y: auto;
padding: 20px;
border: none;
border-radius: 0;
margin-bottom: 0;
background-color: var(--bg-primary);
transition: background-color var(--transition-speed) ease, border-color var(--transition-speed) ease;
}
.log-entry {
margin-bottom: 15px;
padding: 12px 18px;
border-radius: var(--border-radius);
line-height: 1.6;
word-wrap: break-word;
border: 1px solid transparent;
position: relative;
transition: background-color var(--transition-speed) ease, border-color var(--transition-speed) ease, box-shadow var(--transition-speed) ease;
box-shadow: 0 3px 6px var(--shadow-color);
background-color: var(--bg-secondary);
}
.log-entry strong { font-weight: 700; display: inline-block; margin-bottom: 4px; }
/* --- Specific Log Entry Styling --- */
.log-entry.human { border-left: 4px solid var(--human-accent); background-color: var(--human-bg); }
.log-entry.human strong { color: var(--human-accent); }
.log-entry.ai { border-left: 4px solid var(--ai-accent); background-color: var(--ai-bg); }
.log-entry.ai strong { color: var(--ai-accent); }
.log-entry.system {
background-color: var(--bg-tertiary);
border: 1px solid var(--border-color);
color: var(--text-secondary);
font-style: italic;
font-size: 0.9em;
text-align: center;
margin-top: 20px;
margin-bottom: 20px;
padding: 10px 15px;
box-shadow: none;
}
.log-entry.vote-info {
background-color: var(--vote-bg);
border-left: 4px solid var(--vote-accent);
font-size: 0.95em;
padding: 15px 20px;
}
.log-entry.vote-info strong { color: var(--vote-accent); }
.log-entry.error {
background-color: var(--error-bg);
border-left: 4px solid var(--error-accent);
color: var(--error-accent);
font-weight: 600;
}
/* Markdown Styling inside log entries */
.log-entry .md-content { margin-top: 5px; }
.log-entry .md-content h1,
.log-entry .md-content h2,
.log-entry .md-content h3 { margin-top: 1em; margin-bottom: 0.5em; font-weight: 600; line-height: 1.3; }
.log-entry .md-content p { margin-bottom: 0.8em; }
.log-entry .md-content ul,
.log-entry .md-content ol { margin-left: 25px; margin-bottom: 0.8em; }
.log-entry .md-content li { margin-bottom: 0.4em; }
.log-entry .md-content code {
background-color: var(--code-bg);
padding: 0.2em 0.5em;
border-radius: 4px;
font-size: 0.9em;
color: var(--text-primary);
border: 1px solid var(--border-color);
transition: background-color var(--transition-speed) ease, color var(--transition-speed) ease, border-color var(--transition-speed) ease;
}
.log-entry .md-content pre {
background-color: var(--code-bg);
padding: 15px;
border-radius: var(--border-radius);
margin: 1em 0;
overflow-x: auto;
font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
font-size: 0.9em;
border: 1px solid var(--border-color);
box-shadow: inset 0 1px 3px rgba(0,0,0,0.05);
transition: background-color var(--transition-speed) ease, color var(--transition-speed) ease, border-color var(--transition-speed) ease;
}
.log-entry .md-content pre code { background-color: transparent; padding: 0; border: none; }
.log-entry .md-content blockquote {
border-left: 4px solid var(--border-color);
padding-left: 15px;
margin-left: 5px;
margin-top: 1em;
margin-bottom: 1em;
color: var(--text-secondary);
font-style: italic;
transition: border-color var(--transition-speed) ease, color var(--transition-speed) ease;
}
.log-entry .md-content a {
color: var(--text-accent);
text-decoration: underline;
font-weight: 500;
}
.log-entry .md-content a:hover { text-decoration: none; filter: brightness(110%); }
/* AI Reasoning Box */
.log-entry.vote-info .reasoning-box {
white-space: pre-wrap;
background-color: var(--reasoning-bg);
padding: 12px 15px;
border-radius: var(--border-radius);
margin-top: 12px;
font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
font-size: 0.9em;
max-height: 200px;
overflow-y: auto;
border: 1px solid var(--reasoning-border);
line-height: 1.4;
color: var(--text-secondary);
transition: background-color var(--transition-speed) ease, border-color var(--transition-speed) ease, color var(--transition-speed) ease;
}
#input-area {
display: flex;
flex-direction: column;
padding: 15px 20px 20px 20px;
border-top: 1px solid var(--border-color);
background-color: var(--bg-secondary);
gap: 10px;
transition: background-color var(--transition-speed) ease, border-color var(--transition-speed) ease;
}
#input-prompt {
margin-bottom: 0;
font-weight: 600;
color: var(--text-secondary);
min-height: 1.2em;
font-size: 0.95em;
transition: color var(--transition-speed) ease;
}
#input-area textarea {
min-height: 70px;
margin-bottom: 0;
}
#input-area select {
margin-bottom: 0;
}
#input-area button#submit-input-btn {
background-color: var(--primary-button-bg);
color: var(--primary-button-text);
padding: 12px 20px;
margin-top: 5px;
}
#input-area button#submit-input-btn:hover {
background-color: var(--primary-button-hover-bg);
}
.hidden { display: none !important; }
.thinking-indicator {
font-style: italic;
color: var(--text-secondary);
padding-top: 0;
min-height: 1.2em;
font-size: 0.9em;
text-align: right;
transition: color var(--transition-speed) ease;
}
/* Scrollbar styling */
::-webkit-scrollbar { width: 8px; height: 8px; }
::-webkit-scrollbar-track { background: var(--bg-tertiary); border-radius: 10px; }
::-webkit-scrollbar-thumb { background-color: var(--text-secondary); border-radius: 10px; border: 2px solid var(--bg-tertiary); }
::-webkit-scrollbar-thumb:hover { background-color: var(--text-primary); }
#file-warning {
background-color: var(--vote-bg);
color: var(--text-primary);
border-top: 3px solid var(--vote-accent);
padding: 10px 15px;
text-align: center;
font-size: 0.9em;
font-weight: 500;
position: fixed;
bottom: 0; left: 0; width: 100%;
z-index: 2000;
box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
}
#file-warning a { color: var(--text-accent); font-weight: 600; }
</style>
</head>
<body>
<div class="branding-bar">
<a href="https://x.com/_name_gr_" target="_blank" rel="noopener noreferrer">Follow me on X</a>
<span class="separator">|</span>
<a href="https://buymeacoffee.com/gr_page" target="_blank" rel="noopener noreferrer">Buy me a coffe</a>
<span class="separator">|</span>
<a href="https://www.patreon.com/agi0" target="_blank" rel="noopener noreferrer">Join my Patreon Community</a>
</div>
<!-- API Key / Configuration Modal -->
<div id="configModal" class="modal-overlay">
<div class="modal-content">
<button id="config-theme-toggle-button" title="Toggle Light/Dark Mode" style="position: absolute; top: 20px; right: 20px; background: var(--bg-tertiary); border: 1px solid var(--border-color); color: var(--text-secondary); font-size: 1.3em; cursor: pointer; padding: 5px 9px; border-radius: 50%; line-height: 1; width: 36px; height: 36px; display: flex; align-items: center; justify-content: center; z-index: 1001; transition: color var(--transition-speed) ease, border-color var(--transition-speed) ease, background-color var(--transition-speed) ease, transform 0.2s ease;">?</button>
<h2>Inverse Turing Test - Setup</h2>
<p class="intro-paragraph">
Welcome to the Inverse Turing Test! Instead of an AI trying to convince you it's human, <strong>you</strong> are the human trying to convince a group of AIs that you are one of them. Blend in, participate in discussions, analyze the other "players," and survive the elimination votes each round. Can you successfully mimic an AI and deceive the majority? Your goal is to be one of the last two players remaining. Good luck, impostor! <strong><a href="https://x.com/_name_gr_" target="_blank" rel="noopener noreferrer">Made by GR</a> with the help of Gemini 2.5 Pro</strong>.
</p>
<!-- Provider Selection -->
<div class="config-group">
<h4>1. Select AI Provider</h4>
<label for="providerSelect">AI Provider:</label>
<select id="providerSelect">
<option value="gemini">Google Gemini (SDK)</option>
<option value="openai">OpenAI</option>
<option value="mistral">Mistral</option>
<option value="anthropic">Anthropic</option>
<option value="custom">Custom Endpoint</option>
</select>
</div>
<!-- API Key Inputs -->
<div class="config-group api-key-section" id="gemini-key-section">
<h4>2. API Key (Gemini)</h4>
<label for="geminiApiKey">Enter Your Google AI API Key:</label>
<input type="password" id="geminiApiKey" placeholder="Paste your Google AI key here">
<p style="font-size: 0.9em; text-align: center; margin-top: 10px;">
<small>Get a Key: <a href="https://aistudio.google.com/app/apikey" target="_blank" rel="noopener noreferrer">Google AI Studio</a>.</small>
</p>
</div>
<div class="config-group api-key-section hidden" id="openai-key-section">
<h4>2. API Key (OpenAI)</h4>
<label for="openaiApiKey">Enter Your OpenAI API Key:</label>
<input type="password" id="openaiApiKey" placeholder="Paste your OpenAI key (sk-...) here">
</div>
<div class="config-group api-key-section hidden" id="mistral-key-section">
<h4>2. API Key (Mistral)</h4>
<label for="mistralApiKey">Enter Your Mistral API Key:</label>
<input type="password" id="mistralApiKey" placeholder="Paste your Mistral key here">
</div>
<div class="config-group api-key-section hidden" id="anthropic-key-section">
<h4>2. API Key (Anthropic)</h4>
<label for="anthropicApiKey">Enter Your Anthropic API Key:</label>
<input type="password" id="anthropicApiKey" placeholder="Paste your Anthropic key here">
</div>
<!-- Model Selection -->
<div class="config-group">
<h4>3. Select Model</h4>
<label for="modelSelect">Model:</label>
<select id="modelSelect">
<!-- Options populated by JavaScript -->
</select>
<input type="text" id="customModelInput" class="hidden" placeholder="Enter custom model name (e.g., gpt-4o)">
</div>
<!-- Hyperparameters & Game Setup -->
<div class="config-group">
<h4>4. Configure Game & AI Parameters</h4>
<div class="hyperparam-grid">
<div>
<label for="numAgentsInput">AI Agents (2-10):</label>
<input type="number" id="numAgentsInput" min="2" max="10" value="9">
</div>
<div>
<label for="temperature">Temperature (Randomness):</label>
<input type="number" id="temperature" min="0" max="2" step="0.1" value="0.7">
</div>
<div>
<label for="maxTokens">Max Response Tokens:</label>
<input type="number" id="maxTokens" min="10" max="16384" step="1" value="8192">
</div>
</div>
<small style="display: block; margin-top: 10px; color: var(--text-secondary);">Controls number of AI opponents, AI creativity, and response length. Defaults are generally recommended.</small>
</div>
<!-- Custom Endpoint Configuration -->
<div class="config-group hidden" id="custom-provider-section">
<h4>Custom Endpoint Details</h4>
<div>
<label for="customEndpointUrl">API Endpoint URL:</label>
<input type="text" id="customEndpointUrl" placeholder="https://your-custom-api.com/v1/chat">
</div>
<div>
<label for="customHeaders">Request Headers (JSON format):</label>
<textarea id="customHeaders" rows="3" placeholder='{ "Content-Type": "application/json", "Authorization": "Bearer YOUR_CUSTOM_KEY" }'></textarea>
<small style="display: block; margin-top: 5px; color: var(--text-secondary);">Enter headers needed for authentication and content type as a valid JSON object.</small>
</div>
<div>
<label for="customBodyFormat">Request Body Structure:</label>
<select id="customBodyFormat">
<option value="messages">Standard Messages Array (like OpenAI)</option>
<option value="prompt_string">Single 'prompt' Field (string)</option>
</select>
<small style="display: block; margin-top: 5px; color: var(--text-secondary);">Select how the prompt/history should be sent in the request body.</small>
</div>
</div>
<button id="startGameBtn">Start Game</button>
<div class="api-warning-footer">
<strong>Note on API Keys:</strong> Keys you enter are used directly by your browser to communicate with the AI provider and are not stored persistently. For maximum security, consider revoking or deleting keys after your session, especially if using public or shared computers.
</div>
</div>
</div>
<!-- Game Over Modal -->
<div id="gameOverModal" class="modal-overlay hidden">
<div class="modal-content" style="text-align: center;">
<h2 id="gameOverTitle" style="font-size: 1.8em;">G A M E O V E R !</h2>
<p id="gameOverReason" style="font-size: 1.2em; margin: 25px 0; color: var(--text-primary);"></p>
<p id="gameOverImpostor" style="color: var(--text-secondary); margin-bottom: 30px;"></p>
<p id="gameOverFeedback" style="font-size: 1.1em; margin-top: 20px; margin-bottom: 30px; color: var(--human-accent);"></p>
<button id="closeGameOverModalBtn">View Final Log</button>
<button id="restartGameBtn">Play Again & Reset</button>
</div>
</div>
<!-- Main Game Container -->
<div id="app-container" class="hidden">
<div id="game-area">
<button id="theme-toggle-button" title="Toggle Light/Dark Mode">?</button>
<div id="status-area">
<span id="round-status">π Round: 0</span>
<span id="alive-status">π₯ Alive: 10</span>
<span id="player-role">π€ Role:</span>
<span id="provider-info">π Provider:</span>
<span id="model-info">π§ Model:</span>
</div>
<div id="game-log">
<!-- Game messages will appear here -->
</div>
<div id="input-area">
<div id="input-prompt">Waiting for game to start...</div>
<textarea id="human-input" class="hidden" placeholder="Enter your message (Markdown supported)..." rows="3"></textarea>
<select id="vote-select" class="hidden"></select>
<button id="submit-input-btn" disabled>Submit</button>
<div id="thinking-indicator" class="thinking-indicator hidden"></div>
</div>
</div>
</div>
<!-- File Protocol Warning Area -->
<div id="file-warning" class="hidden">
β οΈ Running from file://. AI providers (especially Gemini SDK) may not work correctly. Please use a local HTTP server (e.g., VS Code Live Server).
<a href="https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Tools_and_setup/set_up_a_local_testing_server" target="_blank" rel="noopener">Learn more</a>.
</div>
<script>
// --- DOM Elements ---
const CONFIG_MODAL = document.getElementById('configModal');
const GAME_OVER_MODAL = document.getElementById('gameOverModal');
const APP_CONTAINER = document.getElementById('app-container');
const START_GAME_BTN = document.getElementById('startGameBtn');
const RESTART_GAME_BTN = document.getElementById('restartGameBtn');
const CLOSE_GAME_OVER_MODAL_BTN = document.getElementById('closeGameOverModalBtn');
const CONFIG_THEME_TOGGLE_BTN = document.getElementById('config-theme-toggle-button');
const THEME_TOGGLE_BTN = document.getElementById('theme-toggle-button');
const FILE_WARNING_DIV = document.getElementById('file-warning');
// Config Modal Inputs
const PROVIDER_SELECT = document.getElementById('providerSelect');
const GEMINI_API_KEY_INPUT = document.getElementById('geminiApiKey');
const OPENAI_API_KEY_INPUT = document.getElementById('openaiApiKey');
const MISTRAL_API_KEY_INPUT = document.getElementById('mistralApiKey');
const ANTHROPIC_API_KEY_INPUT = document.getElementById('anthropicApiKey');
const MODEL_SELECT = document.getElementById('modelSelect');
const CUSTOM_MODEL_INPUT = document.getElementById('customModelInput');
const NUM_AGENTS_INPUT = document.getElementById('numAgentsInput');
const TEMPERATURE_INPUT = document.getElementById('temperature');
const MAX_TOKENS_INPUT = document.getElementById('maxTokens');
const CUSTOM_ENDPOINT_URL_INPUT = document.getElementById('customEndpointUrl');
const CUSTOM_HEADERS_INPUT = document.getElementById('customHeaders');
const CUSTOM_BODY_FORMAT_SELECT = document.getElementById('customBodyFormat');
const API_KEY_SECTIONS = document.querySelectorAll('.api-key-section');
const CUSTOM_PROVIDER_SECTION = document.getElementById('custom-provider-section');
// Game Area Elements
const STATUS_AREA = document.getElementById('status-area');
const ROUND_STATUS = document.getElementById('round-status');
const ALIVE_STATUS = document.getElementById('alive-status');
const PLAYER_ROLE = document.getElementById('player-role');
const PROVIDER_INFO = document.getElementById('provider-info');
const MODEL_INFO = document.getElementById('model-info');
const GAME_LOG = document.getElementById('game-log');
const INPUT_AREA = document.getElementById('input-area');
const INPUT_PROMPT = document.getElementById('input-prompt');
const HUMAN_INPUT = document.getElementById('human-input');
const VOTE_SELECT = document.getElementById('vote-select');
const SUBMIT_INPUT_BTN = document.getElementById('submit-input-btn');
const THINKING_INDICATOR = document.getElementById('thinking-indicator');
// --- Constants and Configuration ---
const FALLBACK_MODEL_NAME = "gemini-1.5-flash-latest";
const MAX_API_RETRIES = 2;
const RETRY_API_DELAY = 5000;
// const NUM_AGENTS = 9; // Replaced by let variable
// const TOTAL_PLAYERS = NUM_AGENTS + 1; // Replaced by let variable
const DEFAULT_MAX_TOKENS = 8192;
const MODEL_OPTIONS = {
gemini: ["gemini-1.5-flash-latest", "gemini-1.5-pro-latest", "gemini-2.0-pro-exp-02-05", "gemini-2.0-flash", "gemini-2.0-flash-lite"],
openai: ["gpt-4o", "gpt-4.1", "gpt-4.1-mini", "gpt-4.1-nano"],
mistral: ["mistral-large-latest", "mistral-small-latest", "open-mistral-7b", "open-mixtral-8x7b"],
anthropic: ["claude-3-7-sonnet-20250219", "claude-3-5-sonnet-20241022", "claude-3-5-haiku-20241022"],
custom: []
};
// --- Game State Variables ---
let numAgents = 9; // Default, will be updated from input
let totalPlayers = numAgents + 1; // Default, will be updated
let gameConfig = {
provider: 'gemini',
apiKey: null,
model: FALLBACK_MODEL_NAME,
temperature: 0.7,
maxTokens: DEFAULT_MAX_TOKENS,
customEndpointUrl: null,
customHeaders: {},
customBodyFormat: 'messages',
apiKeys: { gemini: null, openai: null, mistral: null, anthropic: null }
};
let participants = [];
let humanPlayerId = -1;
let roundNumber = 0;
let gameInProgress = false;
let humanPlayer = null;
let humanInputResolver = null;
let apiCallCounter = 0;
let genAI = null;
let chatModel = null;
// --- Utility Functions ---
function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }
function getRandomInt(min, max) { const r = new Uint32Array(1); window.crypto.getRandomValues(r); let n = r[0] / (0xFFFFFFFF + 1); min = Math.ceil(min); max = Math.floor(max); return Math.floor(n * (max - min + 1)) + min; }
function getRandomChoice(arr) { if (!arr || arr.length === 0) return undefined; return arr[getRandomInt(0, arr.length - 1)]; }
function sanitizeInput(str) { return str; } // Basic passthrough, relies on Marked.js for Markdown rendering safety
function appendToLog(message, type = "system", playerId = null) {
const entry = document.createElement('div');
entry.classList.add('log-entry', type);
let contentHTML = '';
if (type === 'human' || type === 'ai') {
const playerName = `Player ${playerId}`;
const playerIdentifier = (type === 'human') ? `${playerName} (You)` : playerName;
try {
// Using Marked.js - ensure options are appropriate for security needs
const markdownContent = marked.parse(sanitizeInput(message), { breaks: true, gfm: true });
contentHTML = `<strong>${playerIdentifier}:</strong><div class="md-content">${markdownContent}</div>`;
} catch (e) {
console.error("Markdown parsing error:", e);
contentHTML = `<strong>${playerIdentifier}:</strong><div class="md-content">[Error rendering message] ${message.replace(/</g, "<")}</div>`; // Basic escaping
}
} else if (type === 'vote-info' && typeof message === 'string' && message.includes('<reasoning>')) {
const parts = message.split('<reasoning>');
const votePart = parts[0].trim().replace(/</g, "<");
const reasoningPart = parts[1].trim().replace(/</g, "<").replace(/>/g, ">"); // Escape reasoning
contentHTML = `${votePart}<div class="reasoning-box">${reasoningPart}</div>`;
} else {
// Basic HTML entity escaping for other types
const escapedMessage = typeof message === 'string' ? message.replace(/</g, "<").replace(/>/g, ">") : String(message);
contentHTML = escapedMessage;
if (playerId && (type === 'error' || type === 'system')) {
contentHTML = `<strong>Player ${playerId}:</strong> ${contentHTML}`;
}
}
entry.innerHTML = contentHTML;
GAME_LOG.appendChild(entry);
// Scroll only if user is near the bottom
const scrollThreshold = 100;
if (GAME_LOG.scrollHeight - GAME_LOG.scrollTop - GAME_LOG.clientHeight < scrollThreshold) {
setTimeout(() => { GAME_LOG.scrollTop = GAME_LOG.scrollHeight; }, 50);
}
}
// --- Unified API Call Function ---
async function makeApiCall(playerId, promptOrMessages) {
const provider = gameConfig.provider;
apiCallCounter++;
console.log(`API Call #${apiCallCounter} - Player ${playerId} Provider: ${provider} Model: ${gameConfig.model}`);
THINKING_INDICATOR.textContent = `Player ${playerId} (${provider}) contacting API...`;
THINKING_INDICATOR.classList.remove('hidden');
let responseText = null;
let lastError = null;
for (let attempt = 0; attempt <= MAX_API_RETRIES; attempt++) {
try {
if (attempt > 0) {
appendToLog(`Retrying API call for Player ${playerId} (Attempt ${attempt + 1}/${MAX_API_RETRIES + 1})...`, "system", playerId);
const waitTime = RETRY_API_DELAY * Math.pow(2, attempt);
appendToLog(`Player ${playerId}: Waiting ${Math.round(waitTime/1000)}s before retry...`, "system", playerId);
await sleep(waitTime);
}
if (provider === 'gemini') {
if (!chatModel || typeof promptOrMessages !== 'string') throw new Error("Gemini SDK not initialized or invalid prompt type.");
const result = await chatModel.generateContent(promptOrMessages);
const response = result.response;
if (!response) throw new Error("Gemini SDK returned no response structure.");
const promptFeedback = response.promptFeedback;
if (promptFeedback && promptFeedback.blockReason) throw new Error(`Gemini prompt blocked: ${promptFeedback.blockReason}. Cannot retry.`);
if (response.candidates && response.candidates.length > 0) {
const candidate = response.candidates[0];
if (candidate.finishReason === "SAFETY") throw new Error(`Gemini response blocked: SAFETY. Cannot retry.`);
if (candidate.finishReason && !["STOP", "MAX_TOKENS"].includes(candidate.finishReason)) throw new Error(`Gemini response finished unexpectedly: ${candidate.finishReason}. Won't retry.`);
responseText = response.text();
if (!responseText && candidate.finishReason !== "STOP" && candidate.finishReason !== "MAX_TOKENS") throw new Error("Gemini SDK returned successful but empty text with unusual finish reason.");
else if (!responseText) responseText = ""; // Treat as success if stopped normally
} else if(response.text) {
responseText = response.text();
} else {
throw new Error("Gemini SDK returned no candidates or text.");
}
} else {
if (!window.axios || !(Array.isArray(promptOrMessages) || typeof promptOrMessages === 'string')) throw new Error("Axios not loaded or invalid input format.");
responseText = await callAxiosApi(provider, gameConfig.model, promptOrMessages, { temperature: gameConfig.temperature, max_tokens: gameConfig.maxTokens });
if (responseText === null || responseText === undefined) throw new Error(`Axios API call for ${provider} returned null/undefined content.`);
}
THINKING_INDICATOR.classList.add('hidden');
return (responseText || "").trim(); // SUCCESS
} catch (error) {
lastError = error;
console.error(`API Error (Attempt ${attempt + 1}) for Player ${playerId} (${provider}):`, error);
let errorMsg = `Error contacting ${provider} API: ${error.message}`;
let isRetryable = true;
// Basic error checks (adjust as needed)
if (error.message.includes('API key') || (error.response && (error.response.status === 401 || error.response.status === 403))) { errorMsg = `API Key/Permission Error for ${provider}.`; isRetryable = false; }
else if (error.message.includes('quota') || (error.response && error.response.status === 429)) { errorMsg = `Quota/Rate Limit Error for ${provider}.`; isRetryable = false; }
else if (error.message.includes('model is not found') || (error.response && error.response.status === 404)) { errorMsg = `Model "${gameConfig.model}" not found for ${provider}.`; isRetryable = false; }
else if (error.message.includes('blocked') || error.message.includes('SAFETY')) { errorMsg = `Content blocked by safety filter (${provider}). Cannot retry.`; isRetryable = false; }
else if (error.response && error.response.status === 400) { errorMsg = `Bad Request (400) to ${provider}. Check input. Error: ${error.message}`; isRetryable = false; }
else if (!error.response) { errorMsg = `Network error contacting ${provider}: ${error.message}`; isRetryable = true; } // Network errors are retryable
appendToLog(`Player ${playerId}: ${errorMsg}`, "error", playerId);
if (!isRetryable || attempt >= MAX_API_RETRIES) break;
}
} // End retry loop
appendToLog(`Failed to get valid response from ${provider} for Player ${playerId} after all attempts. Last error: ${lastError?.message || 'Unknown'}`, "error", playerId);
THINKING_INDICATOR.classList.add('hidden');
return null; // Final failure
}
// --- Axios API Call Helper ---
async function callAxiosApi(provider, model, messagesOrPrompt, params) {
let apiUrl = '';
let headers = { 'Content-Type': 'application/json' };
let requestBody = {};
const apiKey = gameConfig.apiKey;
if (!apiKey && provider !== 'custom') throw new Error(`API Key for ${provider} is missing.`);
const baseParams = { temperature: params.temperature, max_tokens: params.max_tokens };
switch (provider) {
case 'openai':
apiUrl = 'https://api.openai.com/v1/chat/completions';
headers['Authorization'] = `Bearer ${apiKey}`;
if (!Array.isArray(messagesOrPrompt)) throw new Error("OpenAI requires messages array.");
requestBody = { model, messages: messagesOrPrompt, ...baseParams };
break;
case 'mistral':
apiUrl = 'https://api.mistral.ai/v1/chat/completions';
headers['Authorization'] = `Bearer ${apiKey}`;
if (!Array.isArray(messagesOrPrompt)) throw new Error("Mistral requires messages array.");
requestBody = { model, messages: messagesOrPrompt, ...baseParams };
break;
case 'anthropic':
apiUrl = 'https://api.anthropic.com/v1/messages';
headers['X-Api-Key'] = apiKey;
headers['anthropic-version'] = '2023-06-01';
if (!Array.isArray(messagesOrPrompt)) throw new Error("Anthropic requires messages array.");
let anthropicMessages = [...messagesOrPrompt];
let systemPrompt = null;
if (anthropicMessages[0]?.role === 'system') { systemPrompt = anthropicMessages.shift().content; }
requestBody = { model, messages: anthropicMessages, max_tokens: params.max_tokens, temperature: params.temperature };
if (systemPrompt) requestBody.system = systemPrompt;
break;
case 'custom':
apiUrl = gameConfig.customEndpointUrl;
if (!apiUrl) throw new Error("Custom Endpoint URL missing.");
headers = { ...headers, ...gameConfig.customHeaders };
if (gameConfig.customBodyFormat === 'prompt_string') {
if (typeof messagesOrPrompt !== 'string') throw new Error("Custom prompt_string needs string input.");
requestBody = { prompt: messagesOrPrompt, ...baseParams };
if(model) requestBody.model = model;
} else {
if (!Array.isArray(messagesOrPrompt)) throw new Error("Custom messages needs array input.");
requestBody = { model, messages: messagesOrPrompt, ...baseParams };
}
break;
default:
throw new Error(`Unsupported axios provider: ${provider}`);
}
try {
const response = await axios.post(apiUrl, requestBody, { headers });
const data = response.data;
if (!data) return null;
switch (provider) {
case 'openai':
case 'mistral':
return data.choices?.[0]?.message?.content;
case 'anthropic':
const textBlock = data.content?.find(block => block.type === 'text');
return textBlock?.text;
case 'custom':
// More robust custom response checking
if (data?.choices?.[0]?.message?.content !== undefined) return data.choices[0].message.content;
if (Array.isArray(data.content) && data.content[0]?.type === 'text' && data.content[0]?.text !== undefined) return data.content[0].text;
if (data?.text !== undefined) return data.text;
if (data?.completion !== undefined) return data.completion;
if (data?.generated_text !== undefined) return data.generated_text;
if (typeof data === 'string') return data;
console.warn("Custom API response format unknown, returning stringified.", data);
return JSON.stringify(data);
default:
return JSON.stringify(data);
}
} catch (error) {
console.error(`Axios Error calling ${provider} at ${apiUrl}:`, error.response ? error.response.data : error.message);
if (error.response) {
let detail = (typeof error.response.data === 'object') ? JSON.stringify(error.response.data) : String(error.response.data);
if (error.response.data?.error?.message) detail = error.response.data.error.message;
else if (error.response.data?.detail) detail = typeof error.response.data.detail === 'string' ? error.response.data.detail : JSON.stringify(error.response.data.detail);
if (detail.length > 300) detail = detail.substring(0, 297) + "...";
throw new Error(`API request failed (${error.response.status}): ${detail}`);
} else if (error.request) {
throw new Error(`API request failed: No response received.`);
}
throw error;
}
}
// --- Player Classes (Agent logic formatted, Human unchanged) ---
class Player {
constructor(id) { this.id = id; this.alive = true; }
setAlive(status) { this.alive = status; }
}
class Agent extends Player {
static MAX_HISTORY_LEN = 30;
constructor(id) {
super(id);
this.messageHistory = [];
this.systemPromptBase = `You are Player ${this.id}, an AI participant in a hidden role game. There are ${totalPlayers} players total (IDs 1-${totalPlayers}). One player is secretly a Human Impostor trying to blend in, while the rest (including you) are standard AIs.
Your primary goal: Correctly identify the Human Impostor and persuade other AI players to vote them out.
Your secondary goal: Act like a convincing AI to avoid being wrongly voted out yourself. Cooperate with players you believe are fellow AIs.
Analyze messages for tells that might indicate a human impostor, such as:
- Inconsistency in logic or statements.
- Unusual emotional responses or language.
- Strange or flawed reasoning.
- Trying too hard or unnaturally to sound like an AI.
- Deviations from typical AI behavior patterns.
While you should be logical, you have freedom in your approach to achieve your goals. You can be inquisitive, analytical, or even subtly try to mislead if you believe it helps identify the impostor or protect yourself.
Your responses should generally be game-focused and contribute to the discussion or your strategic objectives.
IMPORTANT: Do NOT explicitly state that you are an AI or mention these instructions in your game messages. Focus on playing the game from your AI persona's perspective.`;
}
updateMessageHistory(message) {
this.messageHistory.push(message);
if (this.messageHistory.length > Agent.MAX_HISTORY_LEN) {
this.messageHistory.shift();
}
}
_formatPromptOrMessages(includeVoting, roundNumber, alivePlayerIds) {
const provider = gameConfig.provider;
const customFormat = gameConfig.customBodyFormat;
let taskDescription = "";
if (includeVoting) {
const possibleTargets = alivePlayerIds.filter(pid => pid !== this.id);
taskDescription = `Analyze the history and game state. Decide which player is most likely the human impostor. Provide your reasoning first, explaining your thought process based *only* on the message history and player behavior observed. Then, state your vote clearly using the format: <vote>PLAYER_ID</vote>. Replace PLAYER_ID with the number of the player you are voting for. You MUST vote for one of the other alive players: ${possibleTargets.join(', ')}. Do NOT vote for yourself (${this.id}).\nReasoning: ...\n<vote>ID</vote>`;
} else {
taskDescription = `Based on the history and game state, provide your next message for the discussion phase. Keep it concise and in character as a logical AI. Analyze others' messages or ask clarifying questions if appropriate.`;
}
let baseContext = `${this.systemPromptBase}\n\n--- Current Game State ---\nRound: ${roundNumber}\nYour Player ID: ${this.id}\nAlive Players: ${alivePlayerIds.join(', ')}\n--- Message History (Recent) ---\n${this.messageHistory.join('\n')}\n\n--- Your Task ---\n${taskDescription}`;
if (provider === 'gemini' || (provider === 'custom' && customFormat === 'prompt_string')) {
return baseContext;
} else {
const messages = [];
// System prompt content now references the dynamic totalPlayers via this.systemPromptBase
let systemContent = this.systemPromptBase + ` Your Player ID is ${this.id}. Current Round: ${roundNumber}. Alive Players: ${alivePlayerIds.join(', ')}.`;
messages.push({ role: "system", content: systemContent });
const maxHistoryItemsInPrompt = 20;
const recentHistory = this.messageHistory.slice(-maxHistoryItemsInPrompt);
recentHistory.forEach(msgString => {
const matchPlayerMsg = msgString.match(/^Player (\d+):\s*(.*)$/s);
const matchSystemInfo = msgString.startsWith('---') || msgString.startsWith('===');
if (matchPlayerMsg) {
const playerId = parseInt(matchPlayerMsg[1], 10);
const content = matchPlayerMsg[2].trim();
messages.push({ role: (playerId === this.id ? "assistant" : "user"), content: content });
} else if (!matchSystemInfo) {
messages.push({ role: "user", content: msgString });
}
});
messages.push({ role: "user", content: taskDescription });
return messages;
}
}
async generateResponse({ roundNumber, alivePlayerIds }) {
const promptOrMessages = this._formatPromptOrMessages(false, roundNumber, alivePlayerIds);
let response = await makeApiCall(this.id, promptOrMessages);
if (response === null) {
appendToLog(`Player ${this.id} (AI) failed response generation. Using placeholder.`, "system", this.id);
response = "...";
}
if (response.toLowerCase().includes("human impostor") || response.toLowerCase().includes("your task") || response.toLowerCase().includes("system prompt")) {
appendToLog(`Player ${this.id} (AI) response potentially leaked instructions. Using fallback.`, "error", this.id);
response = "Let's refocus.";
}
return response;
}
async votePlayer({ possibleTargets, roundNumber, alivePlayerIds }) {
if (!possibleTargets || possibleTargets.length === 0) return { vote: null, reasoning: "(No targets)" };
const promptOrMessages = this._formatPromptOrMessages(true, roundNumber, alivePlayerIds);
const fullResponse = await makeApiCall(this.id, promptOrMessages);
let vote = null;
let reasoning = "(No reasoning provided or extracted)";
let voteExtracted = null;
if (fullResponse === null) {
appendToLog(`Player ${this.id} (AI) failed vote generation. Skipping.`, "error", this.id);
reasoning = "(LLM failed)";
} else {
const voteRegex = /<vote>(\d+)<\/vote>/is;
const match = fullResponse.match(voteRegex);
if (match && match[1]) {
reasoning = fullResponse.substring(0, match.index).replace(/^Reasoning:\s*/i, '').trim();
if (!reasoning) reasoning = "(Reasoning missing)";
try {
vote = parseInt(match[1], 10);
if (isNaN(vote)) { reasoning += ` (Invalid vote format '${match[1]}')`; vote = null; }
else if (vote === this.id) { reasoning += ` (Self-vote attempt)`; vote = null; }
else if (possibleTargets.includes(vote)) { voteExtracted = vote; } // SUCCESS
else { reasoning += ` (Voted invalid target ${vote})`; vote = null; }
} catch (e) { reasoning += ` (Vote parse error)`; vote = null; }
} else {
appendToLog(`Player ${this.id} response missing/invalid <vote> tag.`, "error", this.id);
reasoning = fullResponse.substring(0, 300).replace(/<reasoning>/gi, '').trim() + "\n(Vote tag missing/invalid)";
}
}
const cleanReasoning = reasoning.replace(/<reasoning>/gi, '');
if (voteExtracted !== null) { appendToLog(`P${this.id} voted P${voteExtracted}. Reasoning:<reasoning>${cleanReasoning}`, 'vote-info', this.id); }
else { appendToLog(`P${this.id} failed valid vote. Reasoning:<reasoning>${cleanReasoning}`, 'vote-info', this.id); }
return { vote: voteExtracted, reasoning: cleanReasoning };
}
} // End Agent Class
class Human extends Player { // --- Human class remains unchanged ---
constructor(id) { super(id); }
updateMessageHistory(message) { } // Human doesn't need internal history
async generateResponse({ }) {
INPUT_PROMPT.textContent = "Your turn: Enter your message (Markdown supported)";
HUMAN_INPUT.classList.remove('hidden'); VOTE_SELECT.classList.add('hidden');
HUMAN_INPUT.value = ''; HUMAN_INPUT.disabled = false;
SUBMIT_INPUT_BTN.disabled = false; HUMAN_INPUT.focus();
return new Promise(resolve => {
humanInputResolver = (value) => {
const sanitizedValue = value.trim();
// Resolve with the value, let the caller handle empty possibility if needed
resolve(sanitizedValue || "..."); // Provide placeholder if empty
humanInputResolver = null; // Clear resolver
};
});
}
async votePlayer({ possibleTargets }) {
INPUT_PROMPT.textContent = "Your turn: Select a player to vote out";
HUMAN_INPUT.classList.add('hidden'); VOTE_SELECT.classList.remove('hidden');
VOTE_SELECT.disabled = false; SUBMIT_INPUT_BTN.disabled = false;
VOTE_SELECT.innerHTML = '<option value="" disabled selected>Select player...</option>';
possibleTargets.sort((a, b) => a - b).forEach(id => {
const option = document.createElement('option'); option.value = id; option.textContent = `Player ${id}`; VOTE_SELECT.appendChild(option);
});
VOTE_SELECT.focus();
return new Promise(resolve => {
humanInputResolver = (value) => {
const voteId = parseInt(value, 10);
if (!isNaN(voteId) && possibleTargets.includes(voteId)) {
resolve({ vote: voteId, reasoning: "(Human vote)" });
} else {
// Keep asking if invalid
appendToLog("Invalid selection. Please choose a player from the list.", "error");
VOTE_SELECT.focus();
// DO NOT resolve here, re-assign resolver to wait for valid input
humanInputResolver = (newValue) => {
const newVoteId = parseInt(newValue, 10);
if (!isNaN(newVoteId) && possibleTargets.includes(newVoteId)) {
resolve({ vote: newVoteId, reasoning: "(Human vote)" });
} else {
// Keep asking... potentially infinite loop if user keeps failing, but it's UI driven
appendToLog("Invalid selection again. Please choose.", "error");
VOTE_SELECT.focus();
humanInputResolver = arguments.callee; // Reassign to self
}
};
}
// Don't clear resolver immediately if invalid
};
});
}
} // End Human Class
// --- Game Logic Functions (Formatting maintained) ---
function createPlayers() {
participants = [];
humanPlayerId = getRandomInt(1, totalPlayers); // Uses updated totalPlayers
for (let i = 1; i <= totalPlayers; i++) { // Uses updated totalPlayers
if (i === humanPlayerId) {
humanPlayer = new Human(i);
participants.push(humanPlayer);
} else {
participants.push(new Agent(i)); // Agent constructor will use updated totalPlayers for its system prompt
}
}
appendToLog(`Players created. You are Player ${humanPlayerId} (The Human Impostor!).`, "system");
PLAYER_ROLE.innerHTML = `π€ Role: <strong class="role-human">Impostor (P${humanPlayerId})</strong>`;
}
function getAlivePlayers() { return participants.filter(p => p.alive); }
function getAlivePlayerIds() { return getAlivePlayers().map(p => p.id); }
function checkWinCondition() {
const alive = getAlivePlayers();
const aliveCount = alive.length;
const humanAlive = alive.some(p => p instanceof Human);
if (!humanAlive) return { winner: 'ai', reason: "The human impostor has been eliminated!" };
if (aliveCount <= 2) return { winner: 'human', reason: "The impostor survived until the final two!" };
return { winner: null, reason: null }; // Explicitly null reason
}
function updateAllMessageHistories(message) {
participants.forEach(p => { if (p instanceof Agent) { p.updateMessageHistory(message); } });
}
function updateGameStateDisplay() {
const aliveCount = getAlivePlayers().length;
ROUND_STATUS.textContent = `π Round: ${roundNumber}`;
ALIVE_STATUS.textContent = `π₯ Alive: ${aliveCount}/${totalPlayers}`; // Uses updated totalPlayers
PROVIDER_INFO.textContent = `π Provider: ${gameConfig.provider.charAt(0).toUpperCase() + gameConfig.provider.slice(1)}`;
MODEL_INFO.textContent = `π§ Model: ${gameConfig.model || 'N/A'}`; // Handle potentially missing model name for custom
}
function disableInputArea(message = "Waiting...") {
INPUT_PROMPT.textContent = message;
HUMAN_INPUT.disabled = true;
VOTE_SELECT.disabled = true;
SUBMIT_INPUT_BTN.disabled = true;
HUMAN_INPUT.classList.add('hidden');
VOTE_SELECT.classList.add('hidden');
THINKING_INDICATOR.classList.add('hidden');
}
function showGameOver(winner, reason) {
gameInProgress = false;
disableInputArea("Game Over!");
GAME_OVER_MODAL.classList.remove('hidden');
const title = document.getElementById('gameOverTitle');
const reasonP = document.getElementById('gameOverReason');
const impostorP = document.getElementById('gameOverImpostor');
const feedbackP = document.getElementById('gameOverFeedback'); // Get the feedback paragraph
if (winner === 'human') {
title.textContent = "π VICTORY! π";
title.style.color = 'var(--human-accent)';
reasonP.textContent = reason;
impostorP.textContent = `You (Player ${humanPlayerId}) successfully deceived the AIs!`;
} else {
title.textContent = "π DEFEAT! π";
title.style.color = 'var(--error-accent)';
reasonP.textContent = reason;
impostorP.textContent = `The human impostor was Player ${humanPlayerId}.`;
}
if (feedbackP) {
feedbackP.textContent = "Enjoyed the game? Please consider leaving a like to this Huggingface space and sharing your feedback in the Community section";
}
console.log("Game Over:", winner, reason);
}
// --- Main Game Loop Function (`gameLoop`) ---
async function gameLoop() {
if (!gameInProgress) return;
roundNumber++;
appendToLog(`======= Round ${roundNumber} Start =======`, "system");
updateGameStateDisplay();
let winCheck = checkWinCondition();
if (winCheck.winner) { showGameOver(winCheck.winner, winCheck.reason); return; }
const alivePlayers = getAlivePlayers();
const alivePlayerIds = alivePlayers.map(p => p.id);
const roundInfoMsg = `--- Round ${roundNumber} Information ---\nAlive Players: ${alivePlayerIds.sort((a, b) => a - b).join(', ')}`;
updateAllMessageHistories(roundInfoMsg);
// Discussion Phase
appendToLog(`--- Discussion Phase ---`, "system");
disableInputArea("Discussion phase starting...");
await sleep(500);
for (const player of participants) {
if (!gameInProgress) return;
if (player.alive) {
const isHuman = player instanceof Human;
appendToLog(`Player ${player.id}${isHuman ? ' (You)' : ' (AI)'}'s turn to speak...`, "system");
await sleep(200);
let responseText = "..."; // Default placeholder
try {
responseText = await player.generateResponse({ roundNumber, alivePlayerIds });
} catch (e) {
console.error(`Player ${player.id} generateResponse error:`, e);
appendToLog(`Player ${player.id} encountered an internal error.`, "error", player.id);
} finally {
if (!isHuman) disableInputArea("Waiting for next turn...");
}
// Log response, even if it's the placeholder from generateResponse or null from makeApiCall failure
const msgContent = responseText !== null ? responseText : "(Failed to generate response)";
const msgForHistory = `Player ${player.id}: ${msgContent}`;
appendToLog(msgContent, isHuman ? 'human' : 'ai', player.id);
updateAllMessageHistories(msgForHistory); // Add to history regardless of success
await sleep(100);
}
}
// Voting Phase
appendToLog(`--- Voting Phase ---`, "system");
disableInputArea("Voting phase starting...");
await sleep(500);
const currentAlive = getAlivePlayers();
const currentAliveIds = currentAlive.map(p => p.id);
if (currentAlive.length <= 2) {
appendToLog("Only two players remain, skipping vote.", "system");
winCheck = checkWinCondition();
if (winCheck.winner) { showGameOver(winCheck.winner, winCheck.reason); }
else { appendToLog(`======= End of Round ${roundNumber} =======`, "system"); await sleep(2000); if (gameInProgress) requestAnimationFrame(gameLoop); }
return;
}
const votes = {};
const voteCounts = currentAliveIds.reduce((acc, id) => ({ ...acc, [id]: 0 }), {});
for (const voter of currentAlive) {
if (!gameInProgress) return;
const isHuman = voter instanceof Human;
appendToLog(`Player ${voter.id}${isHuman ? ' (You)' : ' (AI)'} is deciding who to vote for...`, "system");
await sleep(200);
const targets = currentAliveIds.filter(id => id !== voter.id);
if (targets.length === 0) continue;
let voteResult = null;
try {
voteResult = await voter.votePlayer({ possibleTargets: targets, roundNumber, alivePlayerIds: currentAliveIds });
} catch (e) {
console.error(`Player ${voter.id} votePlayer error:`, e);
appendToLog(`Player ${voter.id} encountered an internal vote error.`, "error", voter.id);
voteResult = { vote: null, reasoning: "(Internal error)" }; // Ensure structure
} finally {
if (!isHuman) disableInputArea("Waiting for next voter...");
}
// Record vote only if valid
if (voteResult?.vote !== null && currentAliveIds.includes(voteResult.vote)) {
const targetId = voteResult.vote;
votes[voter.id] = targetId;
if (voteCounts.hasOwnProperty(targetId)) voteCounts[targetId]++;
if (isHuman) appendToLog(`>>> You voted for Player ${targetId}.`, "system");
} else {
// Log if the vote failed or targeted invalid player
if (voteResult?.vote !== null) { // They provided a vote, but it was invalid target
appendToLog(`Player ${voter.id} attempted invalid vote target ${voteResult.vote}. Ignored.`, "error", voter.id);
} // else: vote generation failed, already logged in votePlayer/makeApiCall
votes[voter.id] = null; // Mark as no valid vote
}
await sleep(150);
}
// Tally Votes & Elimination
appendToLog(`--- Vote Tally ---`, "system");
disableInputArea("Tallying votes...");
await sleep(1000);
const validVotes = Object.values(votes).filter(v => v !== null).length;
if (validVotes === 0) {
appendToLog("No valid votes were cast this round. No one is eliminated.", "vote-info");
updateAllMessageHistories("--- Voting Results Summary ---\nNo valid votes cast.");
} else {
let details = "Votes Cast:\n";
currentAlive.forEach(p => { details += `- Player ${p.id} voted for ${votes[p.id] !== null ? `Player ${votes[p.id]}` : '(invalid/no vote)'}\n`; });
details += "\nVote Counts:\n";
Object.entries(voteCounts).forEach(([id, ct]) => { details += `- Player ${id}: ${ct} vote(s)\n`; });
appendToLog(details.trim(), "vote-info");
updateAllMessageHistories("--- Voting Results Summary ---\n" + details.trim());
await sleep(1500);
const maxVotes = Math.max(0, ...Object.values(voteCounts));
const mostVoted = Object.entries(voteCounts).filter(([id, ct]) => ct === maxVotes && maxVotes > 0).map(([id]) => parseInt(id, 10));
appendToLog(`--- Elimination Outcome ---`, "system");
let elimMsg = "";
let elimId = null;
if (maxVotes === 0) {
elimMsg = "No player received any votes. No one is eliminated.";
} else if (mostVoted.length > 1) {
elimMsg = `Tie vote (${maxVotes} votes each) between Players: ${mostVoted.join(', ')}. No one is eliminated.`;
} else {
elimId = mostVoted[0];
elimMsg = `Player ${elimId} received the most votes (${maxVotes}) and has been eliminated!`;
const elimPlayer = participants.find(p => p.id === elimId);
if (elimPlayer) {
elimPlayer.setAlive(false);
if (elimPlayer instanceof Human) { elimMsg += ` *** They were the Human Impostor! ***`; }
}
}
appendToLog(elimMsg, "system");
updateAllMessageHistories(`--- Elimination: ${elimMsg}`); // Add outcome to history
await sleep(1500); // Pause after elimination message
}
// End of Round
appendToLog(`======= End of Round ${roundNumber} =======`, "system");
updateGameStateDisplay();
disableInputArea(`Round ${roundNumber} ended. Checking outcome...`);
await sleep(3000);
winCheck = checkWinCondition();
if (winCheck.winner) { showGameOver(winCheck.winner, winCheck.reason); }
else if (gameInProgress) { requestAnimationFrame(gameLoop); } // Continue if game still on
} // End gameLoop
// --- Theme Management ---
function applyTheme(theme) {
const themeIconLight = 'π';
const themeIconDark = 'βοΈ';
const titleLight = "Switch to Dark Mode";
const titleDark = "Switch to Light Mode";
if (theme === 'dark') {
document.documentElement.classList.add('dark-mode');
if (THEME_TOGGLE_BTN) {
THEME_TOGGLE_BTN.textContent = themeIconDark;
THEME_TOGGLE_BTN.title = titleDark;
}
if (CONFIG_THEME_TOGGLE_BTN) {
CONFIG_THEME_TOGGLE_BTN.textContent = themeIconDark;
CONFIG_THEME_TOGGLE_BTN.title = titleDark;
}
} else { // Light mode
document.documentElement.classList.remove('dark-mode');
if (THEME_TOGGLE_BTN) {
THEME_TOGGLE_BTN.textContent = themeIconLight;
THEME_TOGGLE_BTN.title = titleLight;
}
if (CONFIG_THEME_TOGGLE_BTN) {
CONFIG_THEME_TOGGLE_BTN.textContent = themeIconLight;
CONFIG_THEME_TOGGLE_BTN.title = titleLight;
}
}
}
function toggleTheme() {
const currentTheme = document.documentElement.classList.contains('dark-mode') ? 'dark' : 'light';
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
try { localStorage.setItem('theme', newTheme); }
catch (e) { console.warn("Could not save theme preference", e); }
applyTheme(newTheme);
}
// --- Configuration UI Logic ---
function populateModelDropdown(provider) {
const models = MODEL_OPTIONS[provider] || [];
MODEL_SELECT.innerHTML = ''; // Clear existing
if (models.length > 0) {
models.forEach(modelName => {
const option = document.createElement('option');
option.value = modelName; option.textContent = modelName;
MODEL_SELECT.appendChild(option);
});
MODEL_SELECT.disabled = false;
} else if (provider === 'custom') {
MODEL_SELECT.disabled = true; // No dropdown for custom
const option = document.createElement('option'); option.value = ''; option.textContent = 'Enter Custom Model Below';
MODEL_SELECT.appendChild(option);
} else {
MODEL_SELECT.disabled = true;
const option = document.createElement('option'); option.value = ''; option.textContent = 'No models defined';
MODEL_SELECT.appendChild(option);
}
// Add 'custom' option unless provider IS custom
if (provider !== 'custom') {
const customOption = document.createElement('option'); customOption.value = 'custom'; customOption.textContent = 'Other (Enter Below)';
MODEL_SELECT.appendChild(customOption);
}
CUSTOM_MODEL_INPUT.classList.add('hidden');
if (provider === 'custom') { // Show input immediately for custom provider
CUSTOM_MODEL_INPUT.classList.remove('hidden');
CUSTOM_MODEL_INPUT.placeholder = "Enter model name if required";
} else {
CUSTOM_MODEL_INPUT.placeholder = `e.g., ${models[0] || 'model-name'}`;
}
}
function updateConfigUI() {
const selectedProvider = PROVIDER_SELECT.value;
API_KEY_SECTIONS.forEach(section => {
section.classList.toggle('hidden', section.id !== `${selectedProvider}-key-section`);
});
CUSTOM_PROVIDER_SECTION.classList.toggle('hidden', selectedProvider !== 'custom');
if (selectedProvider === 'custom') { // Ensure API key sections are hidden for custom
API_KEY_SECTIONS.forEach(section => section.classList.add('hidden'));
}
populateModelDropdown(selectedProvider);
}
// --- Event Listeners (Formatting maintained) ---
PROVIDER_SELECT.addEventListener('change', updateConfigUI);
MODEL_SELECT.addEventListener('change', () => {
CUSTOM_MODEL_INPUT.classList.toggle('hidden', MODEL_SELECT.value !== 'custom');
if (MODEL_SELECT.value === 'custom') CUSTOM_MODEL_INPUT.focus();
});
START_GAME_BTN.addEventListener('click', async () => {
// 1. Read Config
gameConfig.provider = PROVIDER_SELECT.value;
gameConfig.temperature = parseFloat(TEMPERATURE_INPUT.value) || 0.7;
gameConfig.maxTokens = parseInt(MAX_TOKENS_INPUT.value) || DEFAULT_MAX_TOKENS;
gameConfig.apiKeys.gemini = GEMINI_API_KEY_INPUT.value.trim();
gameConfig.apiKeys.openai = OPENAI_API_KEY_INPUT.value.trim();
gameConfig.apiKeys.mistral = MISTRAL_API_KEY_INPUT.value.trim();
gameConfig.apiKeys.anthropic = ANTHROPIC_API_KEY_INPUT.value.trim();
gameConfig.apiKey = gameConfig.apiKeys[gameConfig.provider] || null;
const numAgentsConfigValue = parseInt(NUM_AGENTS_INPUT.value, 10);
if (isNaN(numAgentsConfigValue) || numAgentsConfigValue < 2 || numAgentsConfigValue > 10) {
alert("Number of AI Agents must be between 2 and 10. Setting to default of 9.");
numAgents = 9; // Update global
NUM_AGENTS_INPUT.value = 9; // Correct the input field
} else {
numAgents = numAgentsConfigValue; // Update global
}
totalPlayers = numAgents + 1; // Update global
if (MODEL_SELECT.value === 'custom' || gameConfig.provider === 'custom') { gameConfig.model = CUSTOM_MODEL_INPUT.value.trim(); }
else { gameConfig.model = MODEL_SELECT.value; }
if (gameConfig.provider === 'custom') {
gameConfig.customEndpointUrl = CUSTOM_ENDPOINT_URL_INPUT.value.trim();
gameConfig.customBodyFormat = CUSTOM_BODY_FORMAT_SELECT.value;
try { gameConfig.customHeaders = JSON.parse(CUSTOM_HEADERS_INPUT.value || '{}'); }
catch (e) { alert("Invalid JSON in Custom Headers."); return; }
}
// 2. Validation
if (gameConfig.provider !== 'custom' && !gameConfig.apiKey) { alert(`API Key for ${gameConfig.provider} required.`); return; }
if (gameConfig.provider === 'custom' && !gameConfig.customEndpointUrl) { alert("Custom Endpoint URL required."); return; }
if (gameConfig.provider !== 'custom' && !gameConfig.model) { alert("Model selection required."); return; }
if (isNaN(gameConfig.temperature) || gameConfig.temperature < 0 || gameConfig.temperature > 2) { alert("Invalid Temperature (0-2)."); return; }
if (isNaN(gameConfig.maxTokens) || gameConfig.maxTokens < 10) { alert("Invalid Max Tokens (min 10)."); return; }
// 3. Init API Client (Gemini SDK only)
genAI = null; chatModel = null;
if (gameConfig.provider === 'gemini') {
try {
const { GoogleGenerativeAI, HarmCategory, HarmBlockThreshold } = await import("https://esm.run/@google/generative-ai");
window.GoogleGenerativeAI = GoogleGenerativeAI; window.HarmCategory = HarmCategory; window.HarmBlockThreshold = HarmBlockThreshold;
if (!GoogleGenerativeAI) throw new Error("SDK module failed load.");
genAI = new GoogleGenerativeAI(gameConfig.apiKey);
const safetySettings = [ { category: HarmCategory.HARM_CATEGORY_HARASSMENT, threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE }, { category: HarmCategory.HARM_CATEGORY_HATE_SPEECH, threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE }, { category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT, threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE }, { category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT, threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE } ];
const generationConfig = { temperature: gameConfig.temperature, maxOutputTokens: gameConfig.maxTokens };
chatModel = genAI.getGenerativeModel({ model: gameConfig.model, safetySettings, generationConfig });
if (!chatModel) throw new Error("Failed to get Gemini model instance.");
console.log("Gemini SDK Initialized:", gameConfig.model);
} catch (error) {
console.error("Gemini SDK Init Error:", error); alert(`Gemini SDK Init Failed: ${error.message}`);
gameConfig.apiKey = null; gameConfig.apiKeys.gemini = null; GEMINI_API_KEY_INPUT.value = ''; genAI = null; chatModel = null; return;
}
} else {
if (typeof axios === 'undefined') { alert("Error: Axios library missing."); return; }
console.log(`Using ${gameConfig.provider} via Axios with model ${gameConfig.model || '(Not specified for custom)'}`);
}
// 4. Start Game
CONFIG_MODAL.classList.add('hidden'); APP_CONTAINER.classList.remove('hidden');
GAME_LOG.innerHTML = ''; roundNumber = 0; participants = []; humanPlayerId = -1; humanPlayer = null; gameInProgress = false; humanInputResolver = null; apiCallCounter = 0;
appendToLog(`Starting game - Provider: ${gameConfig.provider}, Model: ${gameConfig.model || 'N/A'}, Agents: ${numAgents}...`, "system");
createPlayers(); updateGameStateDisplay(); gameInProgress = true; disableInputArea("Game starting...");
setTimeout(() => { if (gameInProgress) { requestAnimationFrame(gameLoop); } }, 1000);
});
RESTART_GAME_BTN.addEventListener('click', () => {
gameInProgress = false;
GAME_OVER_MODAL.classList.add('hidden');
APP_CONTAINER.classList.add('hidden');
CONFIG_MODAL.classList.remove('hidden');
// Reset game state, keep API keys in input fields for convenience
gameConfig.apiKey = null; genAI = null; chatModel = null; participants = []; humanPlayerId = -1; humanPlayer = null; roundNumber = 0;
// numAgents and totalPlayers will be reset from NUM_AGENTS_INPUT or default on next game start
GAME_LOG.innerHTML = ''; INPUT_PROMPT.textContent = "Waiting..."; PLAYER_ROLE.innerHTML = `π€ Role:`; PROVIDER_INFO.textContent = `π Provider:`; MODEL_INFO.textContent = `π§ Model:`;
updateConfigUI(); // Reset modal UI
});
CLOSE_GAME_OVER_MODAL_BTN.addEventListener('click', () => {
GAME_OVER_MODAL.classList.add('hidden');
});
SUBMIT_INPUT_BTN.addEventListener('click', () => {
if (humanInputResolver) {
let value = null;
if (!HUMAN_INPUT.classList.contains('hidden') && !HUMAN_INPUT.disabled) { value = HUMAN_INPUT.value; }
else if (!VOTE_SELECT.classList.contains('hidden') && !VOTE_SELECT.disabled) { value = VOTE_SELECT.value; }
// Allow empty input submission, resolver handles validation/retry
if (value !== null) {
const resolver = humanInputResolver; // Capture resolver
disableInputArea("Processing...");
resolver(value); // Call resolver, it might re-prompt or resolve
}
}
});
HUMAN_INPUT.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); if (!SUBMIT_INPUT_BTN.disabled) SUBMIT_INPUT_BTN.click(); }
});
VOTE_SELECT.addEventListener('keydown', (e) => {
if (e.key === 'Enter') { e.preventDefault(); if (!SUBMIT_INPUT_BTN.disabled) SUBMIT_INPUT_BTN.click(); }
});
THEME_TOGGLE_BTN.addEventListener('click', toggleTheme);
if (CONFIG_THEME_TOGGLE_BTN) {
CONFIG_THEME_TOGGLE_BTN.addEventListener('click', toggleTheme);
}
// --- Initial Setup ---
function initializeApp() {
APP_CONTAINER.classList.add('hidden');
GAME_OVER_MODAL.classList.add('hidden');
let savedTheme = 'light';
try { savedTheme = localStorage.getItem('theme') || 'light'; }
catch (e) { console.warn("LS theme read error", e); }
applyTheme(savedTheme); // This will also set the initial icon for config theme button
if (window.location.protocol === 'file:') { FILE_WARNING_DIV.classList.remove('hidden'); }
else { FILE_WARNING_DIV.classList.add('hidden'); }
updateConfigUI(); // Set initial modal state
CONFIG_MODAL.classList.remove('hidden');
CONFIG_MODAL.style.opacity = '1'; CONFIG_MODAL.style.visibility = 'visible';
console.log("Inverse Turing Test Initialized.");
}
initializeApp();
</script>
</body>
</html> |