fivetech commited on
Commit
40011db
·
verified ·
1 Parent(s): ba73466

Create app.js

Browse files
Files changed (1) hide show
  1. app.js +733 -0
app.js ADDED
@@ -0,0 +1,733 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // AI DEBATE ARENA — V2 (Fases 1-3 + memoria local)
2
+ // Motor: wllama (mismo runtime que Multi-Agent-Debate-MiMo-WebGPU)
3
+ import { Wllama } from 'https://cdn.jsdelivr.net/npm/@wllama/wllama@3.5.1/esm/index.js';
4
+
5
+ /* ================= CONFIG ================= */
6
+ const params = new URLSearchParams(location.search);
7
+ const MODELS = {
8
+ mimo: { label: 'MiMo 9B', repo: 'bartowski/MiMo-V2.6-Distill-Qwen-9B-GGUF', file: 'MiMo-V2.6-Distill-Qwen-9B-Q4_K_M.gguf' },
9
+ qwen: { label: 'Qwen2.5 0.5B', repo: 'Qwen/Qwen2.5-0.5B-Instruct-GGUF', file: 'qwen2.5-0.5b-instruct-q4_k_m.gguf' },
10
+ };
11
+ const MOCK = params.get('mock') === '1'; // gancho de pruebas: motor simulado sin modelo real
12
+ const CONFIG = {
13
+ modelUrl: params.get('modelUrl') || '',
14
+ repo: params.get('repo') || '',
15
+ file: params.get('file') || '',
16
+ nCtx: parseInt(params.get('ctx')) || 8192,
17
+ maxTokens: parseInt(params.get('maxTokens')) || 320,
18
+ temperature: parseFloat(params.get('temp')) || 0.7,
19
+ };
20
+ const WEIGHTS = [
21
+ ['argumentacion', 'Calidad argumentativa', 25],
22
+ ['logica', 'Razonamiento lógico', 25],
23
+ ['evidencia', 'Evidencias', 20],
24
+ ['refutacion', 'Refutación', 15],
25
+ ['adaptabilidad', 'Adaptabilidad', 10],
26
+ ['claridad', 'Claridad', 5],
27
+ ];
28
+ const JUDGES = [
29
+ { id: 'logic', name: 'Logic Judge', emoji: '🧠', criteria: ['logica', 'claridad'], desc: 'Coherencia y estructura lógica' },
30
+ { id: 'evidence', name: 'Evidence Judge', emoji: '📚', criteria: ['evidencia', 'argumentacion'], desc: 'Calidad de evidencias y afirmaciones' },
31
+ { id: 'strategy', name: 'Strategy Judge', emoji: '♟️', criteria: ['refutacion', 'adaptabilidad'], desc: 'Capacidad de respuesta y adaptación' },
32
+ ];
33
+ const MODES = [
34
+ { id: 'duel', name: '1 vs 1 — Duel', desc: 'Dos agentes se enfrentan en rondas alternas. Ideal para debates intensos.', live: true },
35
+ { id: 'ffa', name: 'Free For All', desc: 'Hasta ocho agentes defienden sus propias posiciones.', live: true },
36
+ { id: 'team', name: 'Team Battle', desc: 'Dos equipos de agentes colaboran y compiten entre sí.', live: false },
37
+ { id: 'tournament', name: 'Survival Tournament', desc: 'Eliminatorias: el ganador avanza hasta la gran final.', live: false },
38
+ ];
39
+ const STRATEGY_TEXT = {
40
+ attack: 'Estrategia ATTACK: busca debilidades en los argumentos de tus rivales y atácalas con precisión. Señala exactamente qué afirmación es débil y por qué.',
41
+ defense: 'Estrategia DEFENSE: protege tu posición. Refuerza tus puntos fuertes y responde a cada objeción que te hayan hecho.',
42
+ evidence: 'Estrategia EVIDENCE: prioriza evidencias, datos y razonamientos verificables sobre la retórica.',
43
+ socratic: 'Estrategia SOCRATIC: cuestiona mediante preguntas incisivas que expongan las contradicciones de tus rivales.',
44
+ counterattack: 'Estrategia COUNTERATTACK: responde directamente a cada objeción recibida con un contraargumento concreto.',
45
+ };
46
+ const ADAPTIVE_CYCLE = ['attack', 'defense', 'evidence', 'socratic', 'counterattack'];
47
+ const PHASES = [
48
+ { id: 'opening', label: 'Opening' },
49
+ { id: 'crossfire', label: 'Crossfire' },
50
+ { id: 'rebuttal', label: 'Rebuttal' },
51
+ { id: 'closing', label: 'Closing' },
52
+ { id: 'judging', label: 'Judging' },
53
+ { id: 'verdict', label: 'Verdict' },
54
+ ];
55
+ const DEFAULT_AGENTS = [
56
+ { id: 'professor', name: 'The Professor', emoji: '🔬', color: '#3B82F6', specialty: 'Ciencia', style: 'Analítico', strategy: 'evidence',
57
+ stats: { logic: 95, creativity: 72, aggression: 35 },
58
+ system: 'Eres The Professor, científico analítico. Razonas con precisión, citas mecanismos y datos, y distingues lo demostrado de lo especulativo.' },
59
+ { id: 'strategist', name: 'The Strategist', emoji: '♟️', color: '#8B5CF6', specialty: 'Estrategia', style: 'Calculador', strategy: 'counterattack',
60
+ stats: { logic: 90, creativity: 68, aggression: 55 },
61
+ system: 'Eres The Strategist, un calculador. Piensas dos movimientos por delante, explotas las concesiones del rival y conviertes sus argumentos en los tuyos.' },
62
+ { id: 'skeptic', name: 'The Skeptic', emoji: '🧐', color: '#F59E0B', specialty: 'Pensamiento crítico', style: 'Escéptico', strategy: 'socratic',
63
+ stats: { logic: 92, creativity: 60, aggression: 50 },
64
+ system: 'Eres The Skeptic. No aceptas nada sin pruebas: cuestionas supuestos, pides evidencia y señalas falacias. Duro con las ideas, respetuoso con las personas.' },
65
+ { id: 'innovator', name: 'The Innovator', emoji: '💡', color: '#10B981', specialty: 'Tecnología', style: 'Creativo', strategy: 'attack',
66
+ stats: { logic: 70, creativity: 96, aggression: 60 },
67
+ system: 'Eres The Innovator, mente creativa tecnológica. Propones escenarios audaces, conexiones inesperadas y visiones de futuro, y defiendes la experimentación.' },
68
+ { id: 'philosopher', name: 'The Philosopher', emoji: '🏛️', color: '#EC4899', specialty: 'Filosofía', style: 'Socrático', strategy: 'defense',
69
+ stats: { logic: 88, creativity: 80, aggression: 30 },
70
+ system: 'Eres The Philosopher. Examinas los fundamentos éticos y conceptuales del tema, defines los términos con cuidado y defiendes tu posición con coherencia.' },
71
+ { id: 'economist', name: 'The Economist', emoji: '📊', color: '#14B8A6', specialty: 'Economía', style: 'Pragmático', strategy: 'evidence',
72
+ stats: { logic: 85, creativity: 55, aggression: 45 },
73
+ system: 'Eres The Economist, pragmático. Evalúas incentivos, costes y beneficios, y traes el debate a consecuencias medibles y trade-offs reales.' },
74
+ { id: 'challenger', name: 'The Challenger', emoji: '⚔️', color: '#EF4444', specialty: 'Argumentación', style: 'Agresivo', strategy: 'attack',
75
+ stats: { logic: 75, creativity: 65, aggression: 95 },
76
+ system: 'Eres The Challenger, combativo y directo. Atacas los argumentos rivales sin rodeos, con energía y contundencia, pero siempre con razones.' },
77
+ { id: 'synthesizer', name: 'The Synthesizer', emoji: '🤝', color: '#6366F1', specialty: 'Síntesis', style: 'Conciliador', strategy: 'adaptive',
78
+ stats: { logic: 80, creativity: 78, aggression: 25 },
79
+ system: 'Eres The Synthesizer. Integras lo mejor de cada posición, encuentras síntesis y cambias de táctica según evoluciona el debate.' },
80
+ ];
81
+ const TOPIC_POOL = [
82
+ '¿Debería la IA tener derechos legales?', '¿Es la exploración espacial una buena inversión pública?',
83
+ '¿Redes sociales: más beneficio o más daño?', '¿Debería ser obligatoria la semana laboral de 4 días?',
84
+ '¿Superará la IA a los médicos en diagnóstico?', '¿Es el arte generado por IA verdadero arte?',
85
+ '¿Deberían prohibirse los coches de combustión en 2035?', '¿Es la privacidad un derecho absoluto?',
86
+ '¿Nuclear o renovables para la transición energética?', '¿Debería haber un límite de riqueza personal?',
87
+ '¿Es la educación online tan válida como la presencial?', '¿Deberían los algoritmos recomendadores ser auditados?',
88
+ '¿Es el teletrabajo mejor que la oficina?', '¿Debería existir una renta básica universal?',
89
+ '¿Son los videojuegos cultura?', '¿Debería la ingeniería genética humana ser legal?',
90
+ ];
91
+ const EMOJIS = ['🔬','♟️','🧐','💡','🏛️','📊','⚔️','🤝','🦊','🐺','🦁','🐉','🤖','👾','🎯','🔥','🌊','⚡','🧭','🎭'];
92
+ const COLORS = ['#3B82F6','#8B5CF6','#F59E0B','#10B981','#EC4899','#14B8A6','#EF4444','#6366F1','#F97316','#84CC16','#06B6D4','#A855F7'];
93
+
94
+ /* ================= STATE MANAGER ================= */
95
+ const LS = {
96
+ get(k, d) { try { const v = JSON.parse(localStorage.getItem(k)); return v ?? d; } catch { return d; } },
97
+ set(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch (e) { console.warn('persist fail', e); } },
98
+ };
99
+ let agents = LS.get('arena_agents', null) || structuredClone(DEFAULT_AGENTS);
100
+ let stats = LS.get('arena_stats', {}); // id -> {wins,losses,draws,scoreSum,matches,awards:{}}
101
+ let matches = LS.get('arena_matches', []); // últimas 10 batallas (eventos + veredicto)
102
+ let selected = LS.get('arena_selected', ['professor', 'challenger']);
103
+ let mode = 'duel';
104
+ let wllama = null, modelKey = null;
105
+ let battle = null; // estado de la batalla activa
106
+ let replayTimer = null;
107
+ let running = false, stopRequested = false;
108
+
109
+ /* ================= HELPERS ================= */
110
+ const $ = s => document.querySelector(s);
111
+ function esc(s) { const d = document.createElement('div'); d.textContent = s; return d.innerHTML; }
112
+ function agentById(id) { return agents.find(a => a.id === id); }
113
+ function shade(hex, amt) {
114
+ const n = parseInt(hex.slice(1), 16);
115
+ let r = (n >> 16) + amt, g = ((n >> 8) & 255) + amt, b = (n & 255) + amt;
116
+ r = Math.max(0, Math.min(255, r)); g = Math.max(0, Math.min(255, g)); b = Math.max(0, Math.min(255, b));
117
+ return '#' + ((r << 16) | (g << 8) | b).toString(16).padStart(6, '0');
118
+ }
119
+ function strategyOf(agent, round) {
120
+ if (agent.strategy !== 'adaptive') return agent.strategy;
121
+ return ADAPTIVE_CYCLE[(round - 1 + DEFAULT_AGENTS.findIndex(d => d.id === agent.id) + 20) % ADAPTIVE_CYCLE.length];
122
+ }
123
+ function md(t) { return (typeof marked !== 'undefined') ? marked.parse(t) : esc(t).replace(/\n/g, '<br>'); }
124
+ function persistAll() { LS.set('arena_agents', agents); LS.set('arena_stats', stats); LS.set('arena_matches', matches); LS.set('arena_selected', selected); }
125
+
126
+ /* ================= NAV ================= */
127
+ document.querySelectorAll('nav button').forEach(b => b.addEventListener('click', () => showView(b.dataset.view)));
128
+ function showView(v) {
129
+ if (v !== 'battle' && replayTimer) { clearInterval(replayTimer); replayTimer = null; }
130
+ document.querySelectorAll('.view').forEach(s => s.classList.remove('active'));
131
+ $('#view-' + v).classList.add('active');
132
+ document.querySelectorAll('nav button').forEach(b => b.classList.toggle('active', b.dataset.view === v));
133
+ if (v === 'hall') renderHall();
134
+ if (v === 'roadmap') renderRoadmap();
135
+ if (v === 'roster') renderRoster();
136
+ if (v === 'lobby') renderLobby();
137
+ }
138
+
139
+ /* ================= LOBBY ================= */
140
+ function renderModes() {
141
+ $('#modes').innerHTML = MODES.map(m => `
142
+ <div class="mode-card ${m.id === mode ? 'sel' : ''} ${m.live ? '' : 'soon'}" data-mode="${m.id}">
143
+ <span class="badge ${m.live ? 'live' : 'dev'}">${m.live ? 'DISPONIBLE' : 'EN DESARROLLO'}</span>
144
+ <h3>${m.name}</h3><p>${m.desc}</p>
145
+ </div>`).join('');
146
+ document.querySelectorAll('.mode-card').forEach(c => c.addEventListener('click', () => {
147
+ const m = MODES.find(x => x.id === c.dataset.mode);
148
+ if (!m.live) return;
149
+ mode = m.id;
150
+ if (mode === 'duel' && selected.length > 2) selected = selected.slice(0, 2);
151
+ renderModes(); renderPicked(); renderRoster();
152
+ }));
153
+ }
154
+ function renderPicked() {
155
+ const need = mode === 'duel' ? '2 agentes' : '3-8 agentes';
156
+ $('#picked-line').innerHTML = `<span class="chip">Modo: <b>${MODES.find(m => m.id === mode).name}</b></span>` +
157
+ selected.map(id => { const a = agentById(id); return a ? `<span class="chip" style="border-color:${a.color}">${a.emoji} <b>${esc(a.name)}</b></span>` : ''; }).join('') +
158
+ `<span class="chip" style="color:var(--muted)">necesitas ${need} — selecciona en «Agentes»</span>`;
159
+ }
160
+ function fillTopicPick() {
161
+ const sel = $('#topic-pick');
162
+ sel.querySelectorAll('option:not(:first-child)').forEach(o => o.remove());
163
+ [...TOPIC_POOL].sort(() => Math.random() - .5).slice(0, 10).forEach(t => {
164
+ const o = document.createElement('option'); o.value = t; o.textContent = t; sel.appendChild(o);
165
+ });
166
+ }
167
+ $('#topic-pick').addEventListener('change', e => { if (e.target.value) $('#topic').value = e.target.value; e.target.value = ''; });
168
+ $('#random-match').addEventListener('click', () => {
169
+ mode = 'duel';
170
+ const pool = agents.map(a => a.id);
171
+ selected = [];
172
+ while (selected.length < 2 && pool.length) selected.push(pool.splice(Math.floor(Math.random() * pool.length), 1)[0]);
173
+ $('#topic').value = TOPIC_POOL[Math.floor(Math.random() * TOPIC_POOL.length)];
174
+ $('#rounds').value = String(1 + Math.floor(Math.random() * 3));
175
+ renderModes(); renderPicked(); renderRoster();
176
+ });
177
+ function renderLobby() { renderModes(); renderPicked(); fillTopicPick(); }
178
+
179
+ /* ================= ROSTER ================= */
180
+ function renderRoster() {
181
+ const min = mode === 'duel' ? 2 : 3, max = mode === 'duel' ? 2 : 8;
182
+ $('#pick-count').textContent = `(${selected.length}/${mode === 'duel' ? 2 : '3-8'})`;
183
+ $('#roster').innerHTML = agents.map(a => {
184
+ const st = stats[a.id] || { wins: 0, losses: 0, draws: 0, scoreSum: 0, matches: 0 };
185
+ const avg = st.matches ? (st.scoreSum / st.matches).toFixed(1) : '—';
186
+ return `
187
+ <div class="agent-card ${selected.includes(a.id) ? 'sel' : ''}" data-id="${a.id}" style="--ac:${a.color}">
188
+ <div class="tools">
189
+ <button class="icon-btn" data-edit="${a.id}" title="Editar">✏️</button>
190
+ </div>
191
+ <div class="avatar">${a.emoji}</div>
192
+ <h3>${esc(a.name)}</h3>
193
+ <div class="spec">${esc(a.specialty)}</div>
194
+ <div class="style">${esc(a.style)} · estrategia ${a.strategy.toUpperCase()}</div>
195
+ ${[['Lógica', a.stats.logic], ['Creatividad', a.stats.creativity], ['Agresividad', a.stats.aggression]].map(([k, v]) =>
196
+ `<div class="stat"><span>${k}</span><div class="bar"><div style="width:${v}%"></div></div><b>${v}</b></div>`).join('')}
197
+ <div class="record">🏆 ${st.wins}V · ${st.losses}D · ${st.draws}E · media ${avg} · ${st.matches} batallas</div>
198
+ </div>`;
199
+ }).join('');
200
+ document.querySelectorAll('.agent-card').forEach(c => c.addEventListener('click', e => {
201
+ if (e.target.closest('[data-edit]')) return;
202
+ const id = c.dataset.id;
203
+ if (selected.includes(id)) {
204
+ if (selected.length <= min && selected.length <= 2) { /* permite bajar a 0, se valida al empezar */ }
205
+ selected = selected.filter(x => x !== id);
206
+ } else {
207
+ if (selected.length >= max) selected.shift();
208
+ selected.push(id);
209
+ }
210
+ persistAll(); renderRoster(); renderPicked();
211
+ }));
212
+ document.querySelectorAll('[data-edit]').forEach(b => b.addEventListener('click', () => openAgentModal(b.dataset.edit)));
213
+ }
214
+
215
+ /* ================= AGENT MODAL ================= */
216
+ let editingId = null;
217
+ function openAgentModal(id) {
218
+ editingId = id;
219
+ const a = id ? agentById(id) : { name: '', emoji: '🤖', color: COLORS[0], specialty: '', style: '', strategy: 'attack', system: '', stats: { logic: 70, creativity: 70, aggression: 50 } };
220
+ $('#am-title').textContent = id ? 'Editar agente' : 'Nuevo agente';
221
+ $('#am-name').value = a.name; $('#am-spec').value = a.specialty; $('#am-style').value = a.style;
222
+ $('#am-strategy').value = a.strategy; $('#am-system').value = a.system;
223
+ $('#am-delete').style.display = id ? 'inline-block' : 'none';
224
+ $('#am-emojis').innerHTML = EMOJIS.map(e => `<button data-e="${e}" class="${e === a.emoji ? 'sel' : ''}">${e}</button>`).join('');
225
+ $('#am-colors').innerHTML = COLORS.map(c => `<button data-c="${c}" class="${c === a.color ? 'sel' : ''}" style="background:${c}"></button>`).join('');
226
+ $('#am-emojis').querySelectorAll('button').forEach(b => b.addEventListener('click', () => { $('#am-emojis').querySelectorAll('button').forEach(x => x.classList.remove('sel')); b.classList.add('sel'); }));
227
+ $('#am-colors').querySelectorAll('button').forEach(b => b.addEventListener('click', () => { $('#am-colors').querySelectorAll('button').forEach(x => x.classList.remove('sel')); b.classList.add('sel'); }));
228
+ $('#agent-modal').classList.add('open');
229
+ }
230
+ $('#add-agent').addEventListener('click', () => openAgentModal(null));
231
+ $('#am-cancel').addEventListener('click', () => $('#agent-modal').classList.remove('open'));
232
+ $('#am-save').addEventListener('click', () => {
233
+ const name = $('#am-name').value.trim();
234
+ if (!name) return;
235
+ const emoji = $('#am-emojis .sel')?.dataset.e || '🤖';
236
+ const color = $('#am-colors .sel')?.dataset.c || COLORS[0];
237
+ const data = {
238
+ name, emoji, color,
239
+ specialty: $('#am-spec').value.trim() || 'Generalista',
240
+ style: $('#am-style').value.trim() || 'Libre',
241
+ strategy: $('#am-strategy').value,
242
+ system: $('#am-system').value.trim() || `Eres ${name}, un debatiente agudo y claro.`,
243
+ };
244
+ if (editingId) Object.assign(agentById(editingId), data);
245
+ else agents.push({ id: 'custom_' + Date.now(), stats: { logic: 70, creativity: 70, aggression: 50 }, ...data });
246
+ persistAll(); $('#agent-modal').classList.remove('open'); renderRoster(); renderPicked();
247
+ });
248
+ $('#am-delete').addEventListener('click', () => {
249
+ if (!editingId || agents.length <= 2) return;
250
+ agents = agents.filter(a => a.id !== editingId);
251
+ selected = selected.filter(x => x !== editingId);
252
+ persistAll(); $('#agent-modal').classList.remove('open'); renderRoster(); renderPicked();
253
+ });
254
+
255
+ /* ================= MODEL RUNTIME ================= */
256
+ function setPill(state, text) {
257
+ const p = $('#model-pill'); p.className = state; $('#model-pill-text').textContent = text;
258
+ }
259
+ function setLoad(pct, text) {
260
+ $('#load-bar').style.width = Math.max(0, Math.min(100, pct)) + '%';
261
+ if (text !== undefined) $('#load-status').textContent = text;
262
+ }
263
+ async function ensureModel() {
264
+ if (MOCK) { modelKey = 'mock'; setPill('ready', 'motor simulado (pruebas)'); setLoad(100, 'Motor simulado listo.'); return; }
265
+ const key = $('#model-sel').value;
266
+ const m = CONFIG.repo ? { label: 'personalizado', repo: CONFIG.repo, file: CONFIG.file } : MODELS[key];
267
+ const url = CONFIG.modelUrl || `https://huggingface.co/${m.repo}/resolve/main/${m.file}`;
268
+ if (wllama && modelKey === url) return;
269
+ $('#start-btn').disabled = true;
270
+ setPill('loading', 'cargando ' + m.label + '…');
271
+ setLoad(0, `Descargando ${m.file} (ctx ${CONFIG.nCtx})…`);
272
+ try {
273
+ if (wllama) await wllama.exit();
274
+ wllama = new Wllama({
275
+ 'default': 'https://cdn.jsdelivr.net/npm/@wllama/wllama@3.5.1/esm/wasm/wllama.wasm',
276
+ }, { parallelDownloads: 5 });
277
+ await wllama.loadModelFromUrl(url, {
278
+ n_gpu_layers: 999, n_ctx: CONFIG.nCtx, n_batch: 512,
279
+ n_threads: Math.max(1, Math.min(8, navigator.hardwareConcurrency || 4)),
280
+ progressCallback: ({ loaded, total }) => {
281
+ if (total > 0) {
282
+ const pct = Math.round((loaded / total) * 100);
283
+ setLoad(pct, `Descargando… ${pct}% (${(loaded / 1048576).toFixed(0)} MB)`);
284
+ }
285
+ },
286
+ });
287
+ modelKey = url;
288
+ setLoad(100, `${m.label} listo.`);
289
+ setPill('ready', m.label + ' listo');
290
+ } catch (e) {
291
+ console.error(e);
292
+ setPill('', 'error de carga');
293
+ setLoad(0, 'Error al cargar el modelo: ' + (e?.message || e) + ' — libera espacio del navegador o prueba el modelo ligero.');
294
+ wllama = null; modelKey = null;
295
+ throw e;
296
+ } finally {
297
+ $('#start-btn').disabled = false;
298
+ }
299
+ }
300
+
301
+ const RULES = 'Responde SOLO con tu intervención: 2-5 frases directas, en el idioma del tema. No escribas tu nombre ni prefijos como "Nombre:". No uses listas largas. No repitas argumentos ya expuestos.';
302
+
303
+ async function generate(system, user, maxTokens, onDelta) {
304
+ if (MOCK) {
305
+ let text;
306
+ if (/Head Judge/.test(system)) {
307
+ const m = user.match(/totales: ([^:\n]+):/);
308
+ text = JSON.stringify({ winner: m ? m[1].trim() : 'Empate',
309
+ justification: 'Veredicto simulado: el ganador presentó argumentos más estructurados, respondió mejor a las objeciones y cerró con una síntesis más sólida.',
310
+ decisive: ['Refutación directa en la ronda 1', 'Cierre con síntesis clara'],
311
+ mistakes: ['Alguna generalización sin evidencia'],
312
+ best: ['Apertura con tesis bien delimitada'] });
313
+ } else if (/Judge|juez/.test(system)) {
314
+ const m = user.match(/Participantes: ([^\n]+)/);
315
+ const names = m ? m[1].split(',').map(s => s.trim()) : ['Agente'];
316
+ const scores = {};
317
+ names.forEach((n, i) => { scores[n] = { logica: 8 - i, claridad: 7, evidencia: 8 - i, argumentacion: 7, refutacion: 8 - i, adaptabilidad: 6 }; });
318
+ text = JSON.stringify(scores);
319
+ } else {
320
+ const who = (user.match(/Ahora intervienes tú, ([^.]+)\./) || [,''])[1];
321
+ text = `Intervención simulada de ${who}. Defiendo mi posición con un argumento principal y un ejemplo concreto. Respondo a la objeción anterior con un contraargumento breve. Mantengo mi tesis con matices.`;
322
+ }
323
+ let shown = '';
324
+ for (let i = 0; i < text.length; i += 12) {
325
+ if (stopRequested) return shown;
326
+ shown = text.slice(0, i + 12);
327
+ if (onDelta) onDelta(shown);
328
+ await new Promise(r => setTimeout(r, 8));
329
+ }
330
+ return text;
331
+ }
332
+ const stream = await wllama.createChatCompletion({
333
+ messages: [{ role: 'system', content: system }, { role: 'user', content: user }],
334
+ max_tokens: maxTokens || CONFIG.maxTokens, temperature: CONFIG.temperature, stream: true,
335
+ });
336
+ let out = '';
337
+ for await (const chunk of stream) {
338
+ if (stopRequested) break;
339
+ const tk = chunk.choices?.[0]?.delta?.content || '';
340
+ if (tk) { out += tk; if (onDelta) onDelta(out); }
341
+ }
342
+ return out.replace(/^\s*(?:\*\*)?[A-Za-zÀ-ɏ0-9_ ]{1,30}:\s*/, '').trim();
343
+ }
344
+ function extractJSON(text) {
345
+ const start = text.indexOf('{');
346
+ if (start < 0) return null;
347
+ let depth = 0;
348
+ for (let i = start; i < text.length; i++) {
349
+ if (text[i] === '{') depth++;
350
+ else if (text[i] === '}') { depth--; if (depth === 0) { try { return JSON.parse(text.slice(start, i + 1)); } catch { return null; } } }
351
+ }
352
+ return null;
353
+ }
354
+
355
+ /* ================= BATTLE ENGINE ================= */
356
+ function participants() { return selected.map(agentById).filter(Boolean); }
357
+ function transcriptView(events, maxChars = 9000) {
358
+ const lines = events.map(e => `${e.agent}: ${e.content}`);
359
+ let out = lines.join('\n\n');
360
+ while (out.length > maxChars && lines.length > 2) { lines.splice(1, 1); out = lines.join('\n\n'); }
361
+ return out;
362
+ }
363
+ function renderPhaseTrack(nowId) {
364
+ const order = ['opening', 'crossfire', 'rebuttal', 'closing', 'judging', 'verdict'];
365
+ const nowIdx = order.indexOf(nowId);
366
+ $('#phase-track').innerHTML = PHASES.map(p => {
367
+ const idx = order.indexOf(p.id);
368
+ return `<span class="phase-step ${p.id === nowId ? 'now' : ''} ${idx < nowIdx ? 'done' : ''}">${p.label}</span>`;
369
+ }).join('');
370
+ }
371
+ function renderFighters(turnId) {
372
+ const ps = battle ? battle.participants : participants();
373
+ if (ps.length === 2) {
374
+ $('#fighters').innerHTML = ps.map(a => `
375
+ <div class="fighter ${a.id === turnId ? 'turn' : ''}" style="--ac:${a.color}" id="fighter-${a.id}">
376
+ <div class="avatar">${a.emoji}</div><h3>${esc(a.name)}</h3>
377
+ <div class="strat">${esc(a.specialty)} · ${a.strategy.toUpperCase()}</div>
378
+ </div>`).join('<div class="vs">VS</div>');
379
+ } else {
380
+ $('#fighters').innerHTML = `<div style="grid-column:1/-1;display:flex;gap:8px;flex-wrap:wrap;justify-content:center">` + ps.map(a => `
381
+ <div class="fighter ${a.id === turnId ? 'turn' : ''}" style="--ac:${a.color};padding:9px 14px;min-width:110px" id="fighter-${a.id}">
382
+ <div class="avatar" style="font-size:1.4rem">${a.emoji}</div><h3 style="font-size:.8rem">${esc(a.name)}</h3>
383
+ <div class="strat">${a.strategy.toUpperCase()}</div>
384
+ </div>`).join('') + '</div>';
385
+ }
386
+ }
387
+ function addEvent(agent, phase, content, round, isUser) {
388
+ const ev = { id: 'ev_' + battle.events.length, round, phase, agent: isUser ? 'Tú' : agent.name, agentId: isUser ? 'user' : agent.id, content, ts: new Date().toISOString() };
389
+ battle.events.push(ev);
390
+ const log = $('#battle-log');
391
+ const div = document.createElement('div');
392
+ div.className = 'msg' + (isUser ? ' user' : '');
393
+ div.style.setProperty('--ac', isUser ? '#8b5cf6' : agent.color);
394
+ div.innerHTML = `<div class="mavatar">${isUser ? '⚡' : agent.emoji}</div>
395
+ <div class="mbody"><div class="mhead" style="color:${isUser ? '#8b5cf6' : agent.color}">${isUser ? 'Tú (challenge)' : esc(agent.name)}
396
+ <span class="ph">${phase} · ronda ${round}</span></div>
397
+ <div class="mtext">${md(content)}</div></div>`;
398
+ log.appendChild(div); log.scrollTop = log.scrollHeight;
399
+ return div;
400
+ }
401
+ function addSystemMsg(text) {
402
+ const log = $('#battle-log');
403
+ const div = document.createElement('div');
404
+ div.className = 'msg system';
405
+ div.innerHTML = `<div class="mbody" style="width:100%"><div class="mtext">${esc(text)}</div></div>`;
406
+ log.appendChild(div); log.scrollTop = log.scrollHeight;
407
+ }
408
+ async function agentIntervention(agent, phase, round, extraInstr) {
409
+ const strat = strategyOf(agent, round);
410
+ const system = agent.system + ' ' + (STRATEGY_TEXT[strat] || '') + ' ' + RULES;
411
+ const view = transcriptView(battle.events);
412
+ const phaseInstr = {
413
+ opening: 'Fase OPENING: presenta tu tesis inicial sobre el tema, con tu posición clara.',
414
+ crossfire: 'Fase CROSSFIRE: reacciona a la última intervención; pregunta, presiona o responde según tu estrategia.',
415
+ rebuttal: 'Fase REBUTTAL: refuta el argumento rival más fuerte en tu contra y refuerza tu posición.',
416
+ closing: 'Fase CLOSING: presenta tu conclusión final, tu mejor síntesis para ganar el debate.',
417
+ }[phase] || '';
418
+ const user = `Tema del debate: ${battle.topic}\nRonda ${round} de ${battle.rounds}.\n${phaseInstr}\n${extraInstr || ''}\n\n` +
419
+ (view ? `Intervenciones hasta ahora:\n${view}\n\n` : 'Aún no hay intervenciones.\n\n') +
420
+ `Ahora intervienes tú, ${agent.name}.`;
421
+ const div = document.createElement('div');
422
+ div.className = 'msg streaming'; div.style.setProperty('--ac', agent.color);
423
+ div.innerHTML = `<div class="mavatar">${agent.emoji}</div>
424
+ <div class="mbody"><div class="mhead" style="color:${agent.color}">${esc(agent.name)}
425
+ <span class="ph">${phase} · ronda ${round} · ${strat}</span></div><div class="mtext"></div></div>`;
426
+ const log = $('#battle-log'); log.appendChild(div);
427
+ const textEl = div.querySelector('.mtext');
428
+ setPill('loading', agent.name + ' escribiendo…');
429
+ const answer = await generate(system, user, CONFIG.maxTokens, partial => {
430
+ textEl.textContent = partial; log.scrollTop = log.scrollHeight;
431
+ });
432
+ div.classList.remove('streaming');
433
+ if (stopRequested || !answer) { div.remove(); setPill('ready', modelKey ? 'listo' : 'sin modelo'); return null; }
434
+ textEl.innerHTML = md(answer);
435
+ battle.events.push({ id: 'ev_' + battle.events.length, round, phase, agent: agent.name, agentId: agent.id, content: answer, strategy: strat, ts: new Date().toISOString() });
436
+ setPill('ready', 'listo');
437
+ return answer;
438
+ }
439
+
440
+ function buildSteps(b) {
441
+ const steps = [];
442
+ b.participants.forEach((a, i) => steps.push({ phase: 'opening', round: 1, idx: i }));
443
+ for (let r = 1; r <= b.rounds; r++) {
444
+ b.participants.forEach((a, i) => steps.push({ phase: 'crossfire', round: r, idx: i }));
445
+ b.participants.forEach((a, i) => steps.push({ phase: 'rebuttal', round: r, idx: i }));
446
+ }
447
+ b.participants.forEach((a, i) => steps.push({ phase: 'closing', round: b.rounds, idx: i }));
448
+ return steps;
449
+ }
450
+ const PHASE_BANNER = {
451
+ opening: '📣 Fase OPENING — cada agente presenta su tesis',
452
+ crossfire: '🔥 Ronda {r}/{R} — CROSSFIRE',
453
+ rebuttal: '🛡️ Ronda {r}/{R} — REBUTTAL',
454
+ closing: '🏁 Fase CLOSING — conclusiones finales',
455
+ };
456
+ const PHASE_TRACK_MAP = { opening: 'opening', crossfire: 'crossfire', rebuttal: 'rebuttal', closing: 'closing' };
457
+
458
+ async function runBattle() {
459
+ running = true; stopRequested = false;
460
+ $('#stop-btn').style.display = 'inline-block'; $('#stop-btn').textContent = '⏸ Pausar';
461
+ try {
462
+ if (!battle.steps) battle.steps = buildSteps(battle);
463
+ let lastKey = null;
464
+ for (let s = battle.resume.step || 0; s < battle.steps.length; s++) {
465
+ if (stopRequested) { battle.resume = { step: s }; break; }
466
+ const st = battle.steps[s];
467
+ const a = battle.participants[st.idx];
468
+ if (!a) continue;
469
+ const key = st.phase + ':' + st.round;
470
+ if (key !== lastKey) {
471
+ renderPhaseTrack(PHASE_TRACK_MAP[st.phase]);
472
+ addSystemMsg(PHASE_BANNER[st.phase].replace('{r}', st.round).replace('{R}', battle.rounds));
473
+ lastKey = key;
474
+ // Aviso de cambio de estrategia adaptive al entrar en una nueva ronda de crossfire
475
+ if (st.phase === 'crossfire' && st.round > 1) {
476
+ battle.participants.filter(x => x.strategy === 'adaptive').forEach(x =>
477
+ addSystemMsg(`🔄 ${x.name} (Adaptive) pasa a estrategia ${strategyOf(x, st.round).toUpperCase()} en la ronda ${st.round}`));
478
+ }
479
+ }
480
+ renderFighters(a.id);
481
+ await agentIntervention(a, st.phase, st.round);
482
+ if (stopRequested) { battle.resume = { step: s }; break; }
483
+ battle.resume = { step: s + 1 };
484
+ }
485
+ renderFighters(null);
486
+ if (stopRequested) {
487
+ addSystemMsg('⏸ Batalla en pausa. Pulsa START BATTLE para continuar donde se quedó.');
488
+ } else if (!battle.winner) {
489
+ await runJudging();
490
+ }
491
+ } finally {
492
+ running = false;
493
+ $('#stop-btn').style.display = 'none';
494
+ }
495
+ }
496
+
497
+ /* ================= JUDGES ================= */
498
+ async function runJudging() {
499
+ renderPhaseTrack('judging');
500
+ addSystemMsg('⚖️ Los tres jueces evalúan de forma independiente…');
501
+ const ps = battle.participants;
502
+ const names = ps.map(a => a.name);
503
+ const transcript = transcriptView(battle.events, 12000);
504
+ battle.scores = {}; // agentId -> criterion -> media de jueces
505
+ battle.judgeReports = [];
506
+ ps.forEach(a => battle.scores[a.id] = {});
507
+ for (const j of JUDGES) {
508
+ if (stopRequested) return;
509
+ const critList = j.criteria.map(c => WEIGHTS.find(w => w[0] === c)[1]).join('" y "');
510
+ const system = `Eres ${j.name}, juez de un torneo de debate (${j.desc}). Evalúas SOLO los criterios "${critList}". Eres estricto, independiente y no conoces las puntuaciones de otros jueces.`;
511
+ const user = `Tema: ${battle.topic}\nParticipantes: ${names.join(', ')}\n\nTranscripción:\n${transcript}\n\n` +
512
+ `Puntúa a cada participante de 0 a 10 en cada criterio. Responde SOLO con JSON válido: {"${names[0]}":{"${j.criteria[0]}":N,"${j.criteria[1] || j.criteria[0]}":N},...}`;
513
+ let parsed = null;
514
+ try {
515
+ const out = await generate(system, user, 400);
516
+ parsed = extractJSON(out);
517
+ } catch (e) { console.warn(j.name, e); }
518
+ // fallback heurístico si el JSON no es parseable
519
+ ps.forEach(a => {
520
+ j.criteria.forEach(c => {
521
+ let v = parsed?.[a.name]?.[c];
522
+ if (typeof v !== 'number' || isNaN(v)) {
523
+ const mine = battle.events.filter(e => e.agentId === a.id);
524
+ v = Math.min(10, 4 + mine.length + (mine.reduce((s, e) => s + e.content.length, 0) / 600));
525
+ v = Math.round(v * 10) / 10;
526
+ }
527
+ v = Math.max(0, Math.min(10, v));
528
+ const cur = battle.scores[a.id][c];
529
+ battle.scores[a.id][c] = cur === undefined ? v : Math.round(((cur + v) / 2) * 10) / 10;
530
+ });
531
+ });
532
+ battle.judgeReports.push({ judge: j.name, emoji: j.emoji, parsed });
533
+ addSystemMsg(`${j.emoji} ${j.name} ha entregado su evaluación`);
534
+ }
535
+ // HEAD JUDGE
536
+ let verdict = null;
537
+ try {
538
+ const totals = ps.map(a => ({ name: a.name, total: totalScore(a.id) }));
539
+ const system = 'Eres el Head Judge de un torneo de debate. Consolidas las evaluaciones de tres jueces y produces el veredicto final, con justificación breve y concreta.';
540
+ const user = `Tema: ${battle.topic}\nPuntuaciones ponderadas totales: ${totals.map(t => `${t.name}: ${t.total}`).join(', ')}\n\n` +
541
+ `Transcripción (resumen):\n${transcript.slice(0, 6000)}\n\n` +
542
+ `Responde SOLO con JSON válido: {"winner":"<nombre exacto del ganador o Empate>","justification":"2-4 frases","decisive":["argumento decisivo 1","2"],"mistakes":["error detectado 1","2"],"best":["mejor intervención 1"]}`;
543
+ const out = await generate(system, user, 450);
544
+ verdict = extractJSON(out);
545
+ } catch (e) { console.warn('head judge', e); }
546
+ finalizeBattle(verdict);
547
+ }
548
+ function totalScore(agentId) {
549
+ const s = battle.scores[agentId] || {};
550
+ let t = 0;
551
+ WEIGHTS.forEach(([k, , w]) => { t += (s[k] ?? 5) * w / 100; });
552
+ return Math.round(t * 100) / 100;
553
+ }
554
+ function finalizeBattle(verdict) {
555
+ renderPhaseTrack('verdict');
556
+ const ps = battle.participants;
557
+ const totals = ps.map(a => ({ a, total: totalScore(a.id) })).sort((x, y) => y.total - x.total);
558
+ let winner = null;
559
+ if (verdict && verdict.winner && verdict.winner !== 'Empate') {
560
+ winner = ps.find(a => a.name.toLowerCase() === String(verdict.winner).toLowerCase()) || null;
561
+ }
562
+ if (!winner && totals.length >= 2 && totals[0].total > totals[1].total) winner = totals[0].a;
563
+ battle.winner = winner ? winner.id : null;
564
+ battle.verdict = verdict;
565
+ battle.finishedAt = new Date().toISOString();
566
+ // stats
567
+ ps.forEach(a => {
568
+ const st = stats[a.id] = stats[a.id] || { wins: 0, losses: 0, draws: 0, scoreSum: 0, matches: 0, awards: {} };
569
+ st.matches++;
570
+ st.scoreSum += totalScore(a.id);
571
+ if (!winner) st.draws++;
572
+ else if (a.id === winner.id) st.wins++;
573
+ else st.losses++;
574
+ });
575
+ // guardar batalla (Arena Memory)
576
+ matches.unshift({ id: battle.id, topic: battle.topic, mode: battle.mode, rounds: battle.rounds, participants: ps.map(a => a.id), events: battle.events, scores: battle.scores, winner: battle.winner, verdict, date: battle.finishedAt });
577
+ if (matches.length > 10) matches.length = 10;
578
+ persistAll();
579
+ renderResults(totals, winner, verdict);
580
+ showView('results');
581
+ }
582
+
583
+ /* ================= RESULTS ================= */
584
+ function renderResults(totals, winner, verdict) {
585
+ $('#verdict-hero').innerHTML = `
586
+ <div class="crown">👑</div>
587
+ <h1 style="font-size:1.8rem;font-weight:900">${winner ? `<span style="color:${winner.color}">${winner.emoji} ${esc(winner.name)}</span> gana la batalla` : '🤝 EMPATE'}</h1>
588
+ <p style="color:var(--muted);margin-top:8px;font-size:.9rem">${esc(battle.topic)}</p>
589
+ ${verdict?.justification ? `<p style="max-width:640px;margin:12px auto 0;font-size:.9rem;line-height:1.6">${esc(verdict.justification)}</p>` : ''}`;
590
+ $('#score-table').innerHTML = `
591
+ <tr><th>Criterio (peso)</th>${totals.map(t => `<th style="color:${t.a.color}">${t.a.emoji} ${esc(t.a.name)}</th>`).join('')}</tr>
592
+ ${WEIGHTS.map(([k, label, w]) => `<tr><td>${label} <span style="color:var(--muted)">(${w}%)</span></td>${totals.map(t => `<td>${battle.scores[t.a.id][k] ?? '—'}</td>`).join('')}</tr>`).join('')}
593
+ <tr style="font-weight:800"><td>TOTAL</td>${totals.map(t => `<td style="color:${t.a.color}">${t.total}</td>`).join('')}</tr>`;
594
+ $('#judge-cards').innerHTML = battle.judgeReports.map(r => `
595
+ <div class="judge-card"><h4>${r.emoji} ${r.judge}</h4><p>${r.parsed ? esc(JSON.stringify(r.parsed)) : 'Evaluación heurística (respuesta no estructurada).'}</p></div>`).join('') +
596
+ `<div class="judge-card"><h4>👑 Head Judge</h4><p>${verdict?.justification ? esc(verdict.justification) : 'Veredicto por puntuación ponderada.'}</p>
597
+ ${verdict?.decisive ? `<p style="margin-top:6px"><b>Decisivo:</b> ${verdict.decisive.map(esc).join(' · ')}</p>` : ''}
598
+ ${verdict?.mistakes ? `<p style="margin-top:6px"><b>Errores:</b> ${verdict.mistakes.map(esc).join(' · ')}</p>` : ''}</div>`;
599
+ // awards por criterio
600
+ const awards = [`<span class="award">🏆 ${winner ? esc(winner.name) + ' — Master Debater' : 'Empate honorable'}</span>`];
601
+ [['logica', '🧠 Logic Master'], ['evidencia', '📚 Evidence Champion'], ['refutacion', '🛡️ Best Refutation']].forEach(([k, label]) => {
602
+ const best = [...battle.participants].sort((a, b) => (battle.scores[b.id][k] ?? 0) - (battle.scores[a.id][k] ?? 0))[0];
603
+ if (best) awards.push(`<span class="award">${label}: ${esc(best.name)}</span>`);
604
+ });
605
+ $('#awards').innerHTML = awards.join('');
606
+ }
607
+ $('#rematch-btn').addEventListener('click', () => {
608
+ // Rematch: mismos agentes y tema, conservando personalidad; la estrategia adaptive seguirá variando
609
+ const topic = battle.topic;
610
+ startBattle(topic);
611
+ });
612
+ $('#results-lobby').addEventListener('click', () => showView('lobby'));
613
+
614
+ /* ================= BATTLE CONTROL ================= */
615
+ function startBattle(topic) {
616
+ if (replayTimer) { clearInterval(replayTimer); replayTimer = null; }
617
+ const ps = participants();
618
+ const min = mode === 'duel' ? 2 : 3;
619
+ if (ps.length < min) { alert(`Selecciona al menos ${min} agentes en la pestaña Agentes.`); showView('roster'); return; }
620
+ if (!topic) { $('#topic').focus(); return; }
621
+ battle = {
622
+ id: 'match_' + Date.now(), topic, mode, rounds: parseInt($('#rounds').value) || 2,
623
+ participants: ps, events: [], scores: {}, judgeReports: [],
624
+ resume: { step: 0 }, steps: null, winner: null, verdict: null,
625
+ createdAt: new Date().toISOString(),
626
+ };
627
+ $('#battle-log').innerHTML = '';
628
+ $('#challenge-input').value = '';
629
+ showView('battle');
630
+ renderPhaseTrack('opening');
631
+ renderFighters(null);
632
+ addSystemMsg(`🏟️ ${MODES.find(m => m.id === mode).name} — Tema: «${topic}» — ${battle.rounds} ronda(s)`);
633
+ ensureModel().then(() => runBattle()).catch(() => showView('lobby'));
634
+ }
635
+ $('#start-btn').addEventListener('click', () => {
636
+ if (running) return;
637
+ if (battle && stopRequested && battle.events.length && !battle.winner) {
638
+ // reanudar batalla pausada
639
+ stopRequested = false;
640
+ showView('battle');
641
+ ensureModel().then(() => runBattle()).catch(() => {});
642
+ return;
643
+ }
644
+ startBattle($('#topic').value.trim());
645
+ });
646
+ $('#topic').addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); $('#start-btn').click(); } });
647
+ $('#stop-btn').addEventListener('click', () => { stopRequested = true; $('#stop-btn').textContent = 'Pausando…'; });
648
+ $('#exit-battle').addEventListener('click', () => {
649
+ if (running) stopRequested = true;
650
+ if (replayTimer) { clearInterval(replayTimer); replayTimer = null; }
651
+ showView('lobby');
652
+ });
653
+ function userChallenge() {
654
+ const text = $('#challenge-input').value.trim();
655
+ if (!text || !battle) return;
656
+ $('#challenge-input').value = '';
657
+ const curStep = battle.steps ? battle.steps[Math.min(battle.resume.step || 0, battle.steps.length - 1)] : null;
658
+ addEvent({ name: 'Tú', emoji: '⚡', color: '#8b5cf6' }, 'challenge', text, curStep ? curStep.round : 1, true);
659
+ }
660
+ $('#challenge-btn').addEventListener('click', userChallenge);
661
+ $('#challenge-input').addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); userChallenge(); } });
662
+
663
+ /* ================= HALL OF FAME ================= */
664
+ function renderHall() {
665
+ const rows = agents.map(a => {
666
+ const st = stats[a.id] || { wins: 0, losses: 0, draws: 0, scoreSum: 0, matches: 0 };
667
+ const avg = st.matches ? st.scoreSum / st.matches : 0;
668
+ return { a, st, avg, winrate: st.matches ? Math.round(100 * st.wins / st.matches) : 0 };
669
+ }).sort((x, y) => (y.st.wins - x.st.wins) || (y.avg - x.avg));
670
+ $('#hall-table').innerHTML = `
671
+ <tr><th>Agente</th><th>Victorias</th><th>Media</th><th>Winrate</th><th>Batallas</th><th>Confianza</th></tr>
672
+ ${rows.map(({ a, st, avg, winrate }) => {
673
+ const conf = st.matches < 3 ? '<span class="conf low">baja</span>' : st.matches < 10 ? '<span class="conf mid">media</span>' : '<span class="conf high">alta</span>';
674
+ return `<tr><td><span style="color:${a.color}">${a.emoji} ${esc(a.name)}</span></td><td>${st.wins}</td><td>${st.matches ? avg.toFixed(1) : '—'}</td><td>${st.matches ? winrate + '%' : '—'}</td><td>${st.matches}</td><td>${conf}</td></tr>`;
675
+ }).join('')}`;
676
+ $('#match-list').innerHTML = matches.length ? matches.map(m => {
677
+ const w = m.winner ? agentById(m.winner) : null;
678
+ return `<div class="match-item" data-match="${m.id}">
679
+ <div class="mtopic">${esc(m.topic)}</div>
680
+ <div class="mmeta">${MODES.find(x => x.id === m.mode)?.name || m.mode} · ${m.events.length} intervenciones · ${new Date(m.date).toLocaleString('es')}</div>
681
+ <div class="mmeta">👑 ${w ? esc(w.name) : 'Empate'}</div>
682
+ <button class="btn ghost small" data-replay="${m.id}">▶ Replay</button>
683
+ </div>`;
684
+ }).join('') : '<p style="color:var(--muted);font-size:.85rem">Aún no hay batallas guardadas.</p>';
685
+ document.querySelectorAll('[data-replay]').forEach(b => b.addEventListener('click', e => { e.stopPropagation(); startReplay(b.dataset.replay); }));
686
+ }
687
+
688
+ /* ================= REPLAY ================= */
689
+ async function startReplay(matchId) {
690
+ const m = matches.find(x => x.id === matchId);
691
+ if (!m) return;
692
+ const ps = m.participants.map(agentById).filter(Boolean);
693
+ battle = { id: m.id, topic: m.topic, mode: m.mode, rounds: m.rounds, participants: ps, events: [], resume: { step: 0 } };
694
+ showView('battle');
695
+ renderPhaseTrack('verdict');
696
+ renderFighters(null);
697
+ $('#battle-log').innerHTML = '';
698
+ addSystemMsg(`▶ REPLAY — ${m.topic} (${new Date(m.date).toLocaleString('es')})`);
699
+ if (replayTimer) clearInterval(replayTimer);
700
+ let i = 0;
701
+ replayTimer = setInterval(() => {
702
+ if (i >= m.events.length) {
703
+ clearInterval(replayTimer); replayTimer = null;
704
+ const w = m.winner ? agentById(m.winner) : null;
705
+ addSystemMsg(w ? `👑 Ganador: ${w.name}` : '🤝 Empate');
706
+ return;
707
+ }
708
+ const ev = m.events[i++];
709
+ const a = ev.agentId === 'user' ? { name: 'Tú', emoji: '⚡', color: '#8b5cf6' } : agentById(ev.agentId) || { name: ev.agent, emoji: '🤖', color: '#888' };
710
+ addEvent(a, ev.phase, ev.content, ev.round, ev.agentId === 'user');
711
+ }, 1100);
712
+ }
713
+
714
+ /* ================= ROADMAP ================= */
715
+ function renderRoadmap() {
716
+ const phases = [
717
+ { n: 1, name: 'Arena Foundation', tag: 'done', items: ['Estructura modular', 'Integración con el runtime (wllama)', 'Agent Manager', 'Arena State Manager', 'Sistema de turnos y fases', 'Modalidad 1 vs 1'] },
718
+ { n: 2, name: 'Battle Experience', tag: 'done', items: ['Arena Lobby', 'Selección visual de agentes', 'Live Battle con streaming', 'Crossfire y refutaciones', 'Participación humana (Challenge Agent)'] },
719
+ { n: 3, name: 'Intelligence System', tag: 'partial', items: ['Tres jueces independientes + Head Judge', 'Puntuaciones ponderadas', 'Informe de resultados', 'Pendiente: detector de contradicciones y repeticiones (Referee AI)'] },
720
+ { n: 4, name: 'Tournament Mode', tag: 'partial', items: ['Free For All', 'Pendiente: Team Battle, eliminatorias, rematches con estrategia revisada'] },
721
+ { n: 5, name: 'Memory & Replay', tag: 'partial', items: ['Historial de competiciones (localStorage)', 'Replay de batallas', 'Pendiente: IndexedDB, exportación JSON/Markdown/PDF, memoria persistente de agentes'] },
722
+ { n: 6, name: 'Premium Experience', tag: 'todo', items: ['Animaciones y sonidos', 'Efectos de competición', 'Sistema de logros completo', 'Personalización avanzada', 'Optimización WebGPU', 'Multi-Model Arena'] },
723
+ ];
724
+ const labels = { done: 'DISPONIBLE', partial: 'PARCIAL', todo: 'PENDIENTE' };
725
+ $('#roadmap-list').innerHTML = phases.map(p => `
726
+ <div class="phase ${p.tag}"><h3>Fase ${p.n} — ${p.name} <span class="tag ${p.tag}">${labels[p.tag]}</span></h3>
727
+ <ul>${p.items.map(i => `<li>${esc(i)}</li>`).join('')}</ul></div>`).join('');
728
+ }
729
+
730
+ /* ================= INIT ================= */
731
+ renderLobby();
732
+ renderRoster();
733
+ if (params.get('topic')) $('#topic').value = params.get('topic');