Inverse-Turing-Test / index.html
gr0010's picture
Update index.html
2204706 verified
<!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>