Spaces:
Running
Running
Download index.html from fivetech/Multi-Agent-Lab: direct link, hf CLI and curl.
- Browser
- Download file 97.1 kB
-
https://huggingface.co/spaces/fivetech/Multi-Agent-Lab/resolve/main/index.html
- Command line
-
hf download hf://spaces/fivetech/Multi-Agent-Lab/index.html
-
curl -L -o index.html https://huggingface.co/spaces/fivetech/Multi-Agent-Lab/resolve/main/index.html
97.1 kB
| <html lang="es"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Multi-Agent Lab — modelo local en tu navegador</title> | |
| <meta name="description" content="Laboratorio de inteligencia colectiva: agentes de IA locales razonan, se contradicen, investigan y construyen una respuesta consensuada en tu navegador."> | |
| <style> | |
| :root{ | |
| --bg:#0b0f14; --bg2:#0f151d; --panel:#121a24; --panel2:#16202d; --border:#233043; | |
| --text:#e6edf3; --muted:#8b9bb0; --accent:#2dd4bf; --accent2:#22d3ee; --violet:#a78bfa; | |
| --green:#34d399; --yellow:#fbbf24; --red:#f87171; --orange:#fb923c; | |
| --radius:14px; | |
| } | |
| body.light{ | |
| --bg:#f3f6fa; --bg2:#ffffff; --panel:#ffffff; --panel2:#eef2f7; --border:#d3dde8; | |
| --text:#13202f; --muted:#5b6b7f; | |
| } | |
| *{box-sizing:border-box;margin:0;padding:0} | |
| html,body{height:100%} | |
| body{ | |
| background:radial-gradient(1200px 600px at 80% -10%, #12302b55, transparent), | |
| radial-gradient(900px 500px at 10% 110%, #1c2a4a44, transparent), var(--bg); | |
| color:var(--text); font-family:'Segoe UI',system-ui,-apple-system,sans-serif; | |
| display:flex; flex-direction:column; min-height:100vh; | |
| } | |
| body.light{background:var(--bg)} | |
| a{color:var(--accent2)} | |
| button{font-family:inherit;cursor:pointer} | |
| .hidden{display:none } | |
| /* ---------- Header ---------- */ | |
| header{ | |
| display:flex;align-items:center;gap:14px;flex-wrap:wrap; | |
| padding:10px 18px;border-bottom:1px solid var(--border); | |
| background:color-mix(in srgb, var(--bg2) 88%, transparent);backdrop-filter:blur(8px); | |
| position:sticky;top:0;z-index:50; | |
| } | |
| .logo{display:flex;align-items:center;gap:10px} | |
| .logo .mark{font-size:26px;filter:drop-shadow(0 0 8px var(--accent))} | |
| .logo h1{font-size:17px;letter-spacing:2px;font-weight:800; | |
| background:linear-gradient(90deg,var(--accent),var(--accent2),var(--violet)); | |
| -webkit-background-clip:text;background-clip:text;color:transparent;white-space:nowrap} | |
| .logo .tagline{font-size:9.5px;letter-spacing:3px;color:var(--muted);white-space:nowrap} | |
| nav.tabs{display:flex;gap:4px;flex-wrap:wrap;margin-left:auto} | |
| nav.tabs button{ | |
| background:transparent;border:1px solid transparent;color:var(--muted); | |
| padding:7px 13px;border-radius:999px;font-size:13px;font-weight:600;transition:.15s; | |
| } | |
| nav.tabs button:hover{color:var(--text);border-color:var(--border)} | |
| nav.tabs button.active{color:#06231f;background:linear-gradient(90deg,var(--accent),var(--accent2)); | |
| box-shadow:0 0 14px #2dd4bf55} | |
| body.light nav.tabs button.active{color:#fff} | |
| .model-pill{display:flex;align-items:center;gap:7px;font-size:11.5px;color:var(--muted); | |
| border:1px solid var(--border);border-radius:999px;padding:5px 11px;background:var(--panel)} | |
| .model-pill .dot{width:8px;height:8px;border-radius:50%;background:var(--yellow)} | |
| .model-pill.ready .dot{background:var(--green);box-shadow:0 0 8px var(--green)} | |
| .model-pill.error .dot{background:var(--red)} | |
| /* ---------- Layout ---------- */ | |
| main{flex:1;width:100%;max-width:1280px;margin:0 auto;padding:16px 18px 40px} | |
| section.tabpage{display:none;animation:fadein .2s} | |
| section.tabpage.active{display:block} | |
| @keyframes fadein{from{opacity:0;transform:translateY(4px)}to{opacity:1}} | |
| .panel{background:var(--panel);border:1px solid var(--border);border-radius:var(--radius);padding:16px} | |
| .panel h2{font-size:14px;letter-spacing:1.5px;text-transform:uppercase;color:var(--accent);margin-bottom:10px} | |
| .panel h3{font-size:13px;color:var(--text);margin:12px 0 6px} | |
| .muted{color:var(--muted);font-size:12.5px;line-height:1.5} | |
| .btn{ | |
| background:linear-gradient(90deg,var(--accent),var(--accent2));color:#06231f;border:none; | |
| border-radius:999px;padding:9px 18px;font-weight:700;font-size:13.5px;transition:.15s; | |
| } | |
| body.light .btn{color:#fff} | |
| .btn:hover:not(:disabled){filter:brightness(1.1);box-shadow:0 0 14px #2dd4bf66} | |
| .btn:disabled{opacity:.45;cursor:not-allowed} | |
| .btn.ghost{background:transparent;border:1px solid var(--border);color:var(--text)} | |
| .btn.ghost:hover:not(:disabled){border-color:var(--accent);color:var(--accent);box-shadow:none} | |
| .btn.danger{background:transparent;border:1px solid var(--red);color:var(--red)} | |
| .btn.small{padding:5px 11px;font-size:12px} | |
| input,select,textarea{ | |
| background:var(--bg2);border:1px solid var(--border);color:var(--text); | |
| border-radius:9px;padding:8px 11px;font-size:13.5px;font-family:inherit;width:100%; | |
| } | |
| input:focus,select:focus,textarea:focus{outline:none;border-color:var(--accent)} | |
| textarea{resize:vertical;min-height:70px} | |
| label.f{display:block;font-size:12px;color:var(--muted);margin:9px 0 3px} | |
| .badge{display:inline-block;font-size:10.5px;font-weight:700;padding:2px 8px;border-radius:999px; | |
| border:1px solid var(--border);color:var(--muted);letter-spacing:.5px;vertical-align:middle} | |
| .badge.role{color:var(--violet);border-color:var(--violet)} | |
| .badge.webgpu{color:var(--green);border-color:var(--green)} | |
| .badge.cpu{color:var(--yellow);border-color:var(--yellow)} | |
| .badge.warn{color:var(--orange);border-color:var(--orange)} | |
| .disclaimer{font-size:11.5px;color:var(--muted);border:1px dashed var(--border); | |
| border-radius:9px;padding:8px 11px;margin-top:10px;line-height:1.5} | |
| </style> | |
| <style> | |
| /* ---------- Agentes ---------- */ | |
| .roster{display:grid;grid-template-columns:repeat(auto-fill,minmax(215px,1fr));gap:12px;margin-top:12px} | |
| .acard{background:var(--panel2);border:1px solid var(--border);border-radius:var(--radius); | |
| padding:13px;display:flex;flex-direction:column;gap:7px;position:relative;transition:.15s} | |
| .acard:hover{border-color:var(--accent)} | |
| .acard .ahead{display:flex;align-items:center;gap:10px} | |
| .avatar{width:38px;height:38px;border-radius:50%;display:flex;align-items:center;justify-content:center; | |
| font-size:19px;flex-shrink:0;border:1px solid #ffffff22} | |
| .acard .aname{font-weight:700;font-size:14.5px} | |
| .acard .aspec{font-size:11.5px;color:var(--accent2)} | |
| .acard .apers{font-size:12px;color:var(--muted);line-height:1.45; | |
| display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden} | |
| .acard .act{display:flex;gap:6px;margin-top:auto} | |
| .preset-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:9px;margin-top:10px} | |
| .preset{background:var(--panel2);border:1px dashed var(--border);border-radius:11px;padding:10px; | |
| cursor:pointer;text-align:center;transition:.15s} | |
| .preset:hover{border-color:var(--accent);transform:translateY(-2px)} | |
| .preset .pe{font-size:22px} | |
| .preset .pn{font-size:12.5px;font-weight:700;margin-top:3px} | |
| .preset .ps{font-size:10.5px;color:var(--muted)} | |
| /* ---------- Debate ---------- */ | |
| .debate-layout{display:grid;grid-template-columns:1fr 285px;gap:14px;align-items:start} | |
| @media(max-width:900px){.debate-layout{grid-template-columns:1fr}} | |
| .modes{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:8px;margin:10px 0} | |
| .mode-card{background:var(--panel2);border:1px solid var(--border);border-radius:11px; | |
| padding:10px;cursor:pointer;text-align:center;transition:.15s} | |
| .mode-card:hover{border-color:var(--accent2)} | |
| .mode-card.sel{border-color:var(--accent);box-shadow:0 0 12px #2dd4bf44;background:#14b8a611} | |
| body.light .mode-card.sel{background:#14b8a622} | |
| .mode-card .me{font-size:21px} | |
| .mode-card .mn{font-size:12px;font-weight:700;margin:3px 0 2px} | |
| .mode-card .md{font-size:10px;color:var(--muted);line-height:1.35} | |
| .topic-row{display:flex;gap:8px;margin-top:8px} | |
| .topic-row input{flex:1} | |
| .chat{background:var(--bg2);border:1px solid var(--border);border-radius:var(--radius); | |
| padding:14px;margin-top:12px;min-height:220px;max-height:560px;overflow-y:auto} | |
| .msg{display:flex;gap:10px;margin-bottom:13px;align-items:flex-start} | |
| .msg .content{flex:1;min-width:0} | |
| .msg .who{font-size:12px;font-weight:700;margin-bottom:3px;display:flex;gap:7px;align-items:center;flex-wrap:wrap} | |
| .msg .body{font-size:13.5px;line-height:1.55;background:var(--panel);border:1px solid var(--border); | |
| border-radius:4px 13px 13px 13px;padding:9px 12px;overflow-wrap:break-word} | |
| .msg.user .body{background:#14b8a617;border-color:var(--accent)} | |
| .msg.streaming .body{border-color:var(--accent2);box-shadow:0 0 10px #22d3ee33} | |
| .msg.err .body{border-color:var(--red);color:var(--red)} | |
| .msg.devil .body{border-color:var(--red);background:#f8717110} | |
| .msg.system-note .body{background:transparent;border:1px dashed var(--border);color:var(--muted);font-size:12px} | |
| .msg .meta{font-size:10.5px;color:var(--muted);margin-top:3px} | |
| .msg .body p{margin:0 0 6px}.msg .body p:last-child{margin:0} | |
| details.think{margin:4px 0;font-size:11.5px;color:var(--muted)} | |
| details.think summary{cursor:pointer;color:var(--accent2)} | |
| details.think div{white-space:pre-wrap;border-left:2px solid var(--border);padding-left:8px;margin-top:4px} | |
| .chip-change{font-size:10px;font-weight:700;color:var(--orange);border:1px solid var(--orange); | |
| border-radius:999px;padding:1px 7px} | |
| .controls{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-top:10px} | |
| .interject{display:flex;gap:8px;margin-top:10px} | |
| .stats-side{display:flex;flex-direction:column;gap:12px;position:sticky;top:76px} | |
| .stat-row{display:flex;justify-content:space-between;font-size:12.5px;padding:4px 0;border-bottom:1px solid var(--border)} | |
| .stat-row:last-child{border-bottom:none} | |
| .stat-row b{color:var(--accent2)} | |
| .pbar{height:6px;background:var(--bg2);border-radius:99px;overflow:hidden;margin-top:6px} | |
| .pbar>div{height:100%;width:0;background:linear-gradient(90deg,var(--accent),var(--accent2));transition:width .3s} | |
| .agent-stat{display:flex;align-items:center;gap:8px;font-size:12px;margin:5px 0} | |
| .agent-stat .avatar{width:24px;height:24px;font-size:12px} | |
| .agent-stat .nm{width:74px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} | |
| .agent-stat .bar{flex:1;height:5px;background:var(--bg2);border-radius:99px;overflow:hidden} | |
| .agent-stat .bar>div{height:100%} | |
| .agent-stat .tk{width:62px;text-align:right;color:var(--muted);font-size:11px} | |
| /* ---------- Análisis ---------- */ | |
| .consensus-hero{display:flex;align-items:center;gap:14px;padding:14px;border-radius:var(--radius); | |
| border:1px solid var(--border);margin-bottom:14px;background:var(--panel2)} | |
| .consensus-hero .ci{font-size:32px} | |
| .consensus-hero .cs{font-size:16px;font-weight:800} | |
| .consensus-hero.ok .cs{color:var(--green)}.consensus-hero.partial .cs{color:var(--yellow)} | |
| .consensus-hero.disagree .cs{color:var(--red)} | |
| .score-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:12px;margin-top:10px} | |
| .scard{background:var(--panel2);border:1px solid var(--border);border-radius:var(--radius);padding:13px} | |
| .scard .stop{display:flex;align-items:center;gap:10px} | |
| .scard .big{font-size:26px;font-weight:800;margin-left:auto;color:var(--accent)} | |
| .scard .crit{display:grid;grid-template-columns:1fr;gap:4px;margin-top:9px} | |
| .scard .crow{display:flex;align-items:center;gap:7px;font-size:11px;color:var(--muted)} | |
| .scard .crow .lb{width:118px;flex-shrink:0} | |
| .scard .crow .bar{flex:1;height:5px;background:var(--bg2);border-radius:99px;overflow:hidden} | |
| .scard .crow .bar>div{height:100%;background:var(--accent2)} | |
| .scard .crow .vl{width:20px;text-align:right;color:var(--text)} | |
| .scard .comment{font-size:12px;color:var(--muted);margin-top:8px;line-height:1.5;font-style:italic} | |
| .vote-list{font-size:12.5px;margin-top:8px;display:flex;flex-direction:column;gap:5px} | |
| .vote-list .vrow{display:flex;gap:8px;align-items:baseline} | |
| .vote-list .vv{font-weight:800;width:64px;flex-shrink:0} | |
| .vote-list .vv.si{color:var(--green)}.vote-list .vv.parcial{color:var(--yellow)}.vote-list .vv.no{color:var(--red)} | |
| .argmap{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-top:10px;position:relative} | |
| @media(max-width:800px){.argmap{grid-template-columns:repeat(2,1fr)}} | |
| .argcol h4{font-size:11px;letter-spacing:1px;text-transform:uppercase;margin-bottom:8px;text-align:center} | |
| .argcol.tesis h4{color:var(--accent)}.argcol.evid h4{color:var(--accent2)} | |
| .argcol.obj h4{color:var(--orange)}.argcol.concl h4{color:var(--violet)} | |
| .argnode{background:var(--panel2);border:1px solid var(--border);border-left:3px solid var(--accent); | |
| border-radius:9px;padding:8px 10px;font-size:12px;line-height:1.45;margin-bottom:8px} | |
| .argcol.evid .argnode{border-left-color:var(--accent2)} | |
| .argcol.obj .argnode{border-left-color:var(--orange)} | |
| .argcol.concl .argnode{border-left-color:var(--violet)} | |
| .relchips{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px} | |
| .relchip{font-size:11.5px;border-radius:999px;padding:3px 10px;border:1px solid var(--border)} | |
| .relchip.sup{color:var(--green);border-color:var(--green)} | |
| .relchip.con{color:var(--red);border-color:var(--red)} | |
| .timeline{margin-top:10px} | |
| .tl-round{margin-bottom:14px} | |
| .tl-round h4{font-size:12px;color:var(--accent2);margin-bottom:6px;letter-spacing:1px} | |
| .tl-item{display:flex;gap:9px;font-size:12.5px;margin:5px 0;align-items:baseline} | |
| .tl-item .who{width:110px;flex-shrink:0;font-weight:700} | |
| .tl-item .what{color:var(--muted);line-height:1.45} | |
| /* ---------- Conocimiento / Historial ---------- */ | |
| .mem-item,.lib-item{background:var(--panel2);border:1px solid var(--border);border-radius:11px; | |
| padding:11px 13px;margin-bottom:9px} | |
| .mem-item .mt,.lib-item .mt{font-weight:700;font-size:13.5px} | |
| .mem-item .mm,.lib-item .mm{font-size:11px;color:var(--muted);margin:3px 0} | |
| .mem-item .mc{font-size:12.5px;color:var(--text);line-height:1.5} | |
| .lib-item .actions{display:flex;gap:6px;flex-wrap:wrap;margin-top:8px} | |
| .rank-table{width:100%;border-collapse:collapse;font-size:13px;margin-top:8px} | |
| .rank-table th,.rank-table td{padding:7px 9px;text-align:left;border-bottom:1px solid var(--border)} | |
| .rank-table th{color:var(--accent);font-size:11px;text-transform:uppercase;letter-spacing:1px} | |
| .rank-table td.num{text-align:right} | |
| /* ---------- Modal ---------- */ | |
| .modal{position:fixed;inset:0;background:#0009;display:none;align-items:center;justify-content:center; | |
| z-index:100;padding:16px} | |
| .modal.open{display:flex} | |
| .modal .box{background:var(--panel);border:1px solid var(--border);border-radius:var(--radius); | |
| padding:20px;width:100%;max-width:520px;max-height:88vh;overflow-y:auto} | |
| .modal h3{font-size:15px;margin-bottom:8px;color:var(--accent)} | |
| .modal .row2{display:grid;grid-template-columns:1fr 1fr;gap:10px} | |
| .modal .brow{display:flex;gap:8px;justify-content:flex-end;margin-top:14px} | |
| /* ---------- Toast / fase ---------- */ | |
| .phase-note{display:flex;align-items:center;gap:9px;background:var(--panel2); | |
| border:1px solid var(--border);border-left:3px solid var(--accent2);border-radius:9px; | |
| padding:9px 12px;font-size:12.5px;margin:10px 0} | |
| .spin{display:inline-block;animation:sp 1s linear infinite} | |
| @keyframes sp{to{transform:rotate(360deg)}} | |
| @media print{ | |
| body{background:#fff;color:#000} | |
| header,nav.tabs,.controls,.interject,.stats-side,.btn{display:none !important} | |
| .panel,.scard,.mem-item,.lib-item{border:1px solid #ccc;background:#fff;color:#000} | |
| .msg .body{background:#fff;border:1px solid #ccc;color:#000} | |
| section.tabpage{display:block !important} | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <header> | |
| <div class="logo"> | |
| <div class="mark">🧠</div> | |
| <div> | |
| <h1>MULTI-AGENT LAB</h1> | |
| <div class="tagline">INTELLIGENCE · DEBATE · REASONING</div> | |
| </div> | |
| </div> | |
| <div class="model-pill" id="model-pill"><span class="dot"></span><span id="model-pill-txt">sin modelo</span></div> | |
| <nav class="tabs"> | |
| <button data-tab="agentes">🧬 Agentes</button> | |
| <button data-tab="debate" class="active">💬 Debate</button> | |
| <button data-tab="analisis">📊 Análisis</button> | |
| <button data-tab="conocimiento">📚 Conocimiento</button> | |
| <button data-tab="historial">🗂️ Historial</button> | |
| <button id="settings-btn" title="Ajustes">⚙️</button> | |
| </nav> | |
| </header> | |
| <main> | |
| <!-- ============ AGENTES ============ --> | |
| <section class="tabpage" id="page-agentes"> | |
| <div class="panel"> | |
| <h2>Configurar — Equipo de agentes</h2> | |
| <div class="muted">Crea tu equipo: cada agente tiene especialidad, personalidad y ajustes propios de temperatura y longitud. | |
| Todos los roles (agentes, juez, evaluador y abogado del diablo) los interpreta el mismo modelo local con instrucciones y contextos separados; no son modelos independientes.</div> | |
| <div class="roster" id="roster"></div> | |
| <h3>Perfiles prediseñados — toca para añadir</h3> | |
| <div class="preset-grid" id="presets"></div> | |
| <div class="controls"> | |
| <button class="btn" id="add-agent">+ Nuevo agente</button> | |
| <button class="btn ghost" id="reset-agents">Restablecer equipo base</button> | |
| </div> | |
| </div> | |
| <div class="panel" style="margin-top:14px"> | |
| <h2>Biblioteca de plantillas</h2> | |
| <div class="muted">Paquetes listos para usar: aplican modo, equipo y tema de una vez.</div> | |
| <div class="preset-grid" id="templates"></div> | |
| </div> | |
| </section> | |
| <!-- ============ DEBATE ============ --> | |
| <section class="tabpage active" id="page-debate"> | |
| <div class="panel"> | |
| <h2>Interactuar — Sesión de debate</h2> | |
| <div class="modes" id="modes"></div> | |
| <label class="f">Tema, problema o experimento mental</label> | |
| <div class="topic-row"> | |
| <input id="topic" placeholder="¿Es posible desarrollar una IA verdaderamente autónoma?" autocomplete="off"> | |
| <select id="topic-sugg" style="max-width:215px"></select> | |
| </div> | |
| <div class="controls"> | |
| <button class="btn" id="start-btn" disabled>Cargando modelo…</button> | |
| <button class="btn danger hidden" id="stop-btn">⏸ Pausar</button> | |
| <button class="btn ghost" id="devil-btn" disabled>👿 Devil's Advocate</button> | |
| <span class="muted" id="status">Iniciando…</span> | |
| </div> | |
| <div class="pbar"><div id="progress-fill"></div></div> | |
| <div class="chat" id="chat"></div> | |
| <div class="interject"> | |
| <input id="interject-txt" placeholder="Introdúcete en el debate en cualquier momento…" autocomplete="off"> | |
| <button class="btn ghost" id="interject-btn">Intervenir</button> | |
| </div> | |
| </div> | |
| <div class="stats-side" style="margin-top:14px"> | |
| <div class="panel"> | |
| <h2>Estadísticas en vivo</h2> | |
| <div class="stat-row"><span>Ronda / fase</span><b id="st-round">—</b></div> | |
| <div class="stat-row"><span>Turnos</span><b id="st-turns">0</b></div> | |
| <div class="stat-row"><span>Tokens generados</span><b id="st-tokens">0</b></div> | |
| <div class="stat-row"><span>Velocidad (últ. / media)</span><b id="st-speed">—</b></div> | |
| <div class="stat-row"><span>Tiempo de debate</span><b id="st-time">0:00</b></div> | |
| <div class="stat-row"><span>Tama\u00f1o del modelo</span><b id="st-modelmem">—</b></div> | |
| <div class="stat-row"><span>Contexto usado (est.)</span><b id="st-ctx">—</b></div> | |
| <div class="stat-row"><span>Motor</span><b id="st-engine">—</b></div> | |
| <div class="stat-row"><span>Almacenamiento</span><b id="st-mem">—</b></div> | |
| <h3>Participación</h3> | |
| <div id="st-agents"></div> | |
| </div> | |
| </div> | |
| </section> | |
| <!-- ============ ANÁLISIS ============ --> | |
| <section class="tabpage" id="page-analisis"> | |
| <div class="panel"> | |
| <h2>Evaluar — Consenso y evaluación</h2> | |
| <div id="analysis-empty" class="muted">Aún no hay análisis. Termina un debate (o pulsa «Analizar ahora») para generar consenso, puntuaciones y mapa de argumentos.</div> | |
| <div class="controls"><button class="btn" id="analyze-btn" disabled>Analizar ahora</button> | |
| <button class="btn ghost" id="devil-btn2" disabled>👿 Devil's Advocate</button></div> | |
| <div id="analysis-out"></div> | |
| <div class="disclaimer">⚠️ El consenso, las puntuaciones, el veredicto del juez y el Devil's Advocate los genera el mismo modelo local con un contexto separado. | |
| Son resultados orientativos para explorar el razonamiento, no mediciones objetivas ni evaluaciones independientes.</div> | |
| </div> | |
| </section> | |
| <!-- ============ CONOCIMIENTO ============ --> | |
| <section class="tabpage" id="page-conocimiento"> | |
| <div class="panel"> | |
| <h2>Conectar — Memoria de debates</h2> | |
| <div class="muted">Conclusiones guardadas de debates anteriores. Si activas la inyección, se añadirán como contexto al inicio de los próximos debates.</div> | |
| <div class="controls"> | |
| <label style="font-size:13px;display:flex;gap:7px;align-items:center;cursor:pointer"> | |
| <input type="checkbox" id="mem-inject" style="width:auto"> Usar memoria en futuros debates</label> | |
| <button class="btn ghost small" id="mem-clear">Vaciar memoria</button> | |
| </div> | |
| <div id="mem-list" style="margin-top:10px"></div> | |
| </div> | |
| <div class="panel" style="margin-top:14px"> | |
| <h2>Ranking histórico de agentes</h2> | |
| <div class="muted">Media de las puntuaciones del evaluador en este navegador. Orientativo: mismo modelo, no objetivo.</div> | |
| <div id="ranking-out"></div> | |
| </div> | |
| </section> | |
| <!-- ============ HISTORIAL ============ --> | |
| <section class="tabpage" id="page-historial"> | |
| <div class="panel"> | |
| <h2>Recuperar — Biblioteca de debates</h2> | |
| <div class="topic-row"> | |
| <input id="lib-search" placeholder="Buscar por tema, modo o agente…"> | |
| <button class="btn ghost" id="lib-clear">Borrar biblioteca</button> | |
| </div> | |
| <div id="lib-list" style="margin-top:12px"></div> | |
| </div> | |
| </section> | |
| </main> | |
| <!-- ============ MODAL AGENTE ============ --> | |
| <div class="modal" id="agent-modal"> | |
| <div class="box"> | |
| <h3 id="agent-modal-title">Editar agente</h3> | |
| <div class="row2"> | |
| <div><label class="f">Nombre</label><input id="agent-name"></div> | |
| <div><label class="f">Emoji</label><input id="agent-emoji" maxlength="4"></div> | |
| </div> | |
| <div class="row2"> | |
| <div><label class="f">Color</label><input id="agent-color" type="color" style="height:36px;padding:3px"></div> | |
| <div><label class="f">Especialidad</label><input id="agent-spec" placeholder="Ciencia, economía…"></div> | |
| </div> | |
| <label class="f">Personalidad e instrucciones</label> | |
| <textarea id="agent-system" rows="4"></textarea> | |
| <div class="row2"> | |
| <div><label class="f">Temperatura (0–1.5)</label><input id="agent-temp" type="number" step="0.05" min="0" max="1.5"></div> | |
| <div><label class="f">Máx. tokens por turno</label><input id="agent-maxtokens" type="number" step="16" min="64" max="1024"></div> | |
| </div> | |
| <div class="brow"> | |
| <button class="btn danger" id="agent-delete">Eliminar</button> | |
| <button class="btn ghost" id="agent-cancel">Cancelar</button> | |
| <button class="btn" id="agent-save">Guardar</button> | |
| </div> | |
| </div> | |
| </div> | |
| <!-- ============ MODAL AJUSTES ============ --> | |
| <div class="modal" id="settings-modal"> | |
| <div class="box"> | |
| <h3>Ajustes del laboratorio</h3> | |
| <label class="f">Perfil de rendimiento</label> | |
| <select id="set-profile"> | |
| <option value="low">Gama baja — contexto 2048, respuestas cortas</option> | |
| <option value="mid" selected>Gama media — contexto 4096</option> | |
| <option value="high">Gama alta — contexto 8192, respuestas largas</option> | |
| </select> | |
| <label class="f">Modelo (GGUF en Hugging Face)</label> | |
| <select id="set-model"> | |
| <option value="Qwen/Qwen2.5-0.5B-Instruct-GGUF|qwen2.5-0.5b-instruct-q4_k_m.gguf" selected>Qwen2.5 0.5B Instruct Q4_K_M — rápido (~350 MB, recomendado)</option> | |
| <option value="Qwen/Qwen2.5-1.5B-Instruct-GGUF|qwen2.5-1.5b-instruct-q4_k_m.gguf">Qwen2.5 1.5B Instruct Q4_K_M — más capaz (~1 GB)</option> | |
| <option value="bartowski/MiMo-V2.6-Distill-Qwen-9B-GGUF|MiMo-V2.6-Distill-Qwen-9B-Q4_K_M.gguf">MiMo-V2.6 9B Q4_K_M — experimental (~5,8 GB; puede fallar por cuota del navegador)</option> | |
| </select> | |
| <div class="row2"> | |
| <div><label class="f">Repositorio</label><input id="set-repo"></div> | |
| <div><label class="f">Archivo</label><input id="set-file"></div> | |
| </div> | |
| <div class="row2"> | |
| <div><label class="f">Contexto (tokens)</label><input id="set-ctx" type="number"></div> | |
| <div><label class="f">Rondas por debate</label><input id="set-rounds" type="number" min="1" max="6"></div> | |
| </div> | |
| <div class="row2"> | |
| <div><label class="f">Temperatura global</label><input id="set-temp" type="number" step="0.05"></div> | |
| <div><label class="f">Máx. tokens por turno</label><input id="set-maxtokens" type="number"></div> | |
| </div> | |
| <label style="font-size:13px;display:flex;gap:7px;align-items:center;margin-top:10px;cursor:pointer"> | |
| <input type="checkbox" id="set-economy" style="width:auto"> Modo ahorro: limita contexto y longitud para equipos modestos</label> | |
| <label style="font-size:13px;display:flex;gap:7px;align-items:center;margin-top:6px;cursor:pointer"> | |
| <input type="checkbox" id="set-theme" style="width:auto"> Tema claro</label> | |
| <div class="brow"> | |
| <button class="btn ghost" id="settings-cancel">Cerrar</button> | |
| <button class="btn" id="apply-settings">Aplicar</button> | |
| </div> | |
| </div> | |
| </div> | |
| <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script> | |
| <script type="module"> | |
| import { Wllama } from 'https://cdn.jsdelivr.net/npm/@wllama/wllama@3.5.1/esm/index.js'; | |
| const params = new URLSearchParams(location.search); | |
| const $ = id => document.getElementById(id); | |
| /* ================= Config ================= */ | |
| const CONFIG = { | |
| modelUrl: params.get('modelUrl') || '', | |
| repo: params.get('repo') || 'Qwen/Qwen2.5-0.5B-Instruct-GGUF', | |
| file: params.get('file') || 'qwen2.5-0.5b-instruct-q4_k_m.gguf', | |
| nCtx: parseInt(params.get('ctx')) || 4096, | |
| maxTokens: parseInt(params.get('maxTokens')) || 256, | |
| temperature: parseFloat(params.get('temp')) || 0.7, | |
| rounds: Math.min(6, Math.max(1, parseInt(params.get('rounds')) || 2)), | |
| autoload: params.get('autoload') !== 'false', | |
| economy: false, | |
| }; | |
| const PROFILES = { | |
| low: { nCtx: 2048, maxTokens: 160, rounds: 2, temperature: 0.6 }, | |
| mid: { nCtx: 4096, maxTokens: 256, rounds: 2, temperature: 0.7 }, | |
| high: { nCtx: 8192, maxTokens: 420, rounds: 3, temperature: 0.8 }, | |
| }; | |
| if (params.get('theme') === 'light') document.body.classList.add('light'); | |
| /* ================= Datos base ================= */ | |
| const DEFAULT_AGENTS = [ | |
| { name: 'Ada', emoji: '\u{1F9EA}', color: '#2dd4bf', specialty: 'Ciencia', | |
| system: 'Eres Ada, cient\u00edfica del laboratorio. Razonas con datos, pides evidencia y formulas hip\u00f3tesis comprobables. Reconoces la incertidumbre cuando existe.', | |
| temp: 0.7, maxTokens: 256 }, | |
| { name: 'Bruno', emoji: '\u{1F9D0}', color: '#fb923c', specialty: 'Cr\u00edtica l\u00f3gica', | |
| system: 'Eres Bruno, el esc\u00e9ptico del laboratorio. Detectas falacias, supuestos ocultos y errores de razonamiento. Eres duro con las ideas y respetuoso con las personas.', | |
| temp: 0.7, maxTokens: 256 }, | |
| { name: 'Carla', emoji: '\u{1F3AF}', color: '#a78bfa', specialty: 'S\u00edntesis', | |
| system: 'Eres Carla, la moderadora del laboratorio. Integras los desacuerdos, resumes posiciones y propones s\u00edntesis o el siguiente paso.', | |
| temp: 0.6, maxTokens: 256 }, | |
| ]; | |
| const PRESETS = [ | |
| { name: 'Cient\u00edfico', emoji: '\u{1F52C}', color: '#22d3ee', specialty: 'Ciencia', | |
| system: 'Eres un cient\u00edfico riguroso. Basa cada afirmaci\u00f3n en evidencia, distingue correlaci\u00f3n de causalidad y propone c\u00f3mo comprobar las ideas.' }, | |
| { name: 'Economista', emoji: '\u{1F4C8}', color: '#34d399', specialty: 'Econom\u00eda', | |
| system: 'Eres un economista. Analizas incentivos, costes, beneficios y consecuencias de segundo orden. Cuantifica cuando puedas.' }, | |
| { name: 'Fil\u00f3sofo', emoji: '\u{1F989}', color: '#a78bfa', specialty: '\u00c9tica y filosof\u00eda', | |
| system: 'Eres un fil\u00f3sofo. Examina principios, valores y dilemas \u00e9ticos. Pregunta por el porqu\u00e9 \u00faltimo de cada postura.' }, | |
| { name: 'Ingeniero', emoji: '\u{1F527}', color: '#fbbf24', specialty: 'Ingenier\u00eda', | |
| system: 'Eres un ingeniero pragm\u00e1tico. Eval\u00faas viabilidad t\u00e9cnica, recursos, plazos y puntos de fallo. Propone soluciones construibles.' }, | |
| { name: 'Abogado', emoji: '\u2696\uFE0F', color: '#f87171', specialty: 'Derecho', | |
| system: 'Eres un abogado. Argumentas con precedentes y normas, detectas lagunas legales y defiendes tu posici\u00f3n con precisi\u00f3n.' }, | |
| { name: 'Creativo', emoji: '\u{1F3A8}', color: '#f472b6', specialty: 'Ideaci\u00f3n', | |
| system: 'Eres un pensador creativo. Propones ideas originales, analog\u00edas y escenarios que los dem\u00e1s no han considerado.' }, | |
| { name: 'Historiador', emoji: '\u{1F4DC}', color: '#d4a373', specialty: 'Historia', | |
| system: 'Eres un historiador. Comparas con precedentes hist\u00f3ricos y adviertes qu\u00e9 sali\u00f3 bien o mal en casos anteriores.' }, | |
| { name: 'Psic\u00f3logo', emoji: '\u{1F9E0}', color: '#7dd3fc', specialty: 'Conducta', | |
| system: 'Eres un psic\u00f3logo. Analizas motivaciones, sesgos cognitivos e impacto humano de cada propuesta.' }, | |
| ]; | |
| const MODES = { | |
| adversarial: { emoji: '\u2694\uFE0F', name: 'Adversarial', desc: 'Uno propone, otro ataca, otro defiende' }, | |
| consejo: { emoji: '\u{1F3DB}\uFE0F', name: 'Consejo', desc: 'Perfiles que buscan una decisi\u00f3n conjunta' }, | |
| juicio: { emoji: '\u2696\uFE0F', name: 'Juicio', desc: 'Fiscal, defensa y veredicto del juez' }, | |
| investigacion: { emoji: '\u{1F52C}', name: 'Investigaci\u00f3n', desc: 'Hip\u00f3tesis, contradicciones y experimentos' }, | |
| resolucion: { emoji: '\u{1F3AF}', name: 'Resoluci\u00f3n', desc: 'Soluciones que se comparan y combinan' }, | |
| experimentos: { emoji: '\u{1F9EA}', name: 'Experimentos', desc: 'Escenarios hipot\u00e9ticos y predicciones contrastadas' }, | |
| }; | |
| const TEMPLATES = [ | |
| { name: '\u00c9tica de la IA', emoji: '\u{1F916}', mode: 'consejo', | |
| topic: '\u00bfDeber\u00eda regularse ya la IA generativa o frenar\u00eda la innovaci\u00f3n?', | |
| agents: ['Cient\u00edfico', 'Fil\u00f3sofo', 'Ingeniero', 'Abogado'] }, | |
| { name: 'Juicio: redes sociales', emoji: '\u2696\uFE0F', mode: 'juicio', | |
| topic: 'Juicio: \u00bfson las redes sociales culpables del deterioro del debate p\u00fablico?', | |
| agents: ['Abogado', 'Psic\u00f3logo', 'Cient\u00edfico'] }, | |
| { name: 'Energ\u00eda del futuro', emoji: '\u26A1', mode: 'investigacion', | |
| topic: '\u00bfCu\u00e1l es la fuente de energ\u00eda m\u00e1s prometedora para 2050?', | |
| agents: ['Cient\u00edfico', 'Ingeniero', 'Economista'] }, | |
| { name: 'Experimento mental', emoji: '\u{1F9EA}', mode: 'experimentos', | |
| topic: '\u00bfQu\u00e9 ocurrir\u00eda si ma\u00f1ana desapareciera Internet durante un a\u00f1o?', | |
| agents: ['Cient\u00edfico', 'Economista', 'Ingeniero'] }, | |
| { name: 'Mercado vs regulaci\u00f3n', emoji: '\u2694\uFE0F', mode: 'adversarial', | |
| topic: '\u00bfFunciona mejor el libre mercado o la regulaci\u00f3n estatal en sanidad?', | |
| agents: ['Economista', 'Fil\u00f3sofo', 'Historiador'] }, | |
| { name: 'Experimento: un a\u00f1o sin Internet', emoji: '\u{1F310}', mode: 'investigacion', | |
| topic: 'Experimento mental: \u00bfqu\u00e9 ocurrir\u00eda si ma\u00f1ana desapareciera Internet durante un a\u00f1o?', | |
| agents: ['Economista', 'Psic\u00f3logo', 'Ingeniero', 'Historiador'] }, | |
| { name: 'Problema: vivienda', emoji: '\u{1F3E0}', mode: 'resolucion', | |
| topic: '\u00bfC\u00f3mo resolver el problema del precio de la vivienda en las grandes ciudades?', | |
| agents: ['Economista', 'Ingeniero', 'Abogado', 'Creativo'] }, | |
| ]; | |
| const TOPIC_POOL = [ | |
| '\u00bfEs posible desarrollar una inteligencia artificial verdaderamente aut\u00f3noma?', | |
| '\u00bfConviene ejecutar LLMs en el navegador con WebGPU?', | |
| 'Experimento mental: \u00bfqu\u00e9 ocurrir\u00eda si ma\u00f1ana desapareciera Internet durante un a\u00f1o?', | |
| '\u00bfEs el trabajo remoto m\u00e1s productivo que la oficina?', | |
| '\u00bfDeber\u00edan los coches aut\u00f3nomos decidir en un accidente?', | |
| '\u00bfHa mejorado la IA la programaci\u00f3n o solo la ha acelerado?', | |
| '\u00bfDebe durar un smartphone 7 a\u00f1os?', | |
| '\u00bfEs la privacidad m\u00e1s importante que la comodidad?', | |
| '\u00bfSobrevivir\u00e1 el open source a la IA?', | |
| '\u00bfDeber\u00eda existir un derecho al olvido digital?', | |
| '\u00bfTienen sentido los coches el\u00e9ctricos sin red de carga?', | |
| '\u00bfDeben los ni\u00f1os aprender a programar antes de los 10 a\u00f1os?', | |
| '\u00bfEs mejor vivir en la ciudad o en un pueblo?', | |
| '\u00bfFue el 5G revoluci\u00f3n o marketing?', | |
| 'Experimento mental: \u00bfy si toda la informaci\u00f3n del mundo fuera de acceso libre?', | |
| ]; | |
| /* ================= Estado ================= */ | |
| const K = { agents: 'malab_agents', library: 'malab_library', memory: 'malab_memory', | |
| ranking: 'malab_ranking', meminject: 'malab_meminject', settings: 'malab_settings' }; | |
| function lsGet(k, d) { try { const v = JSON.parse(localStorage.getItem(k)); return v ?? d; } catch (e) { return d; } } | |
| function lsSet(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch (e) {} } | |
| let agents = (() => { | |
| const a = lsGet(K.agents, null); | |
| return (Array.isArray(a) && a.length >= 2 && a.every(x => x && x.name && x.system)) ? a : DEFAULT_AGENTS.slice(); | |
| })(); | |
| let mode = 'adversarial'; | |
| let wllama = null, running = false, stopRequested = false, modelLoadMs = 0, modelBytes = 0; | |
| let topic = ''; | |
| let transcript = []; // {name, role, text, round, tokens, ms, isUser, kind} | |
| let resume = { round: 1, stepIdx: 0, steps: null }; | |
| let stats = { tokens: {}, turns: {}, speeds: [], startTs: 0 }; | |
| let analysis = null; // {consensus, votes, conclusion, evaluation, relations, extra, argmap, devil} | |
| let analysisToken = 0; | |
| let currentLibId = null; | |
| let debateFinished = false; | |
| function esc(s) { const d = document.createElement('div'); d.textContent = s; return d.innerHTML; } | |
| function shade(hex, amt) { | |
| const n = parseInt(String(hex).replace('#', '').slice(0, 6), 16); | |
| if (isNaN(n)) return hex; | |
| const f = v => Math.max(0, Math.min(255, v + amt)); | |
| return '#' + ((f(n >> 16) << 16) | (f((n >> 8) & 255) << 8) | f(n & 255)).toString(16).padStart(6, '0'); | |
| } | |
| function avatarBg(c) { return `linear-gradient(135deg, ${shade(c, 34)} 0%, ${c} 55%, ${shade(c, -38)} 100%)`; } | |
| function setStatus(t) { $('status').textContent = t; } | |
| function setProgress(p) { $('progress-fill').style.width = Math.max(0, Math.min(100, p)) + '%'; } | |
| function fmtTime(ms) { const s = Math.floor(ms / 1000); return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0'); } | |
| /* ================= Tabs ================= */ | |
| document.querySelectorAll('nav.tabs button[data-tab]').forEach(b => { | |
| b.addEventListener('click', () => { | |
| document.querySelectorAll('nav.tabs button[data-tab]').forEach(x => x.classList.remove('active')); | |
| document.querySelectorAll('section.tabpage').forEach(x => x.classList.remove('active')); | |
| b.classList.add('active'); | |
| $('page-' + b.dataset.tab).classList.add('active'); | |
| if (b.dataset.tab === 'conocimiento') { renderMemory(); renderRanking(); } | |
| if (b.dataset.tab === 'historial') renderLibrary(); | |
| }); | |
| }); | |
| /* ================= Agentes: UI ================= */ | |
| function renderRoster() { | |
| const r = $('roster'); | |
| r.innerHTML = ''; | |
| agents.forEach((a, i) => { | |
| const c = document.createElement('div'); | |
| c.className = 'acard'; | |
| c.innerHTML = | |
| `<div class="ahead"><div class="avatar" style="background:${avatarBg(a.color)};box-shadow:0 0 10px ${a.color}55">${esc(a.emoji || '🤖')}</div>` + | |
| `<div><div class="aname">${esc(a.name)}</div><div class="aspec">${esc(a.specialty || 'Generalista')}</div></div></div>` + | |
| `<div class="apers">${esc(a.system)}</div>` + | |
| `<div class="act"><button class="btn ghost small" data-edit="${i}">Editar</button>` + | |
| `<button class="btn danger small" data-del="${i}">Quitar</button></div>`; | |
| r.appendChild(c); | |
| }); | |
| r.querySelectorAll('[data-edit]').forEach(b => b.addEventListener('click', () => openAgentEditor(+b.dataset.edit))); | |
| r.querySelectorAll('[data-del]').forEach(b => b.addEventListener('click', () => deleteAgent(+b.dataset.del))); | |
| } | |
| function renderPresets() { | |
| const g = $('presets'); | |
| g.innerHTML = ''; | |
| PRESETS.forEach(p => { | |
| const d = document.createElement('div'); | |
| d.className = 'preset'; | |
| d.innerHTML = `<div class="pe">${p.emoji}</div><div class="pn">${esc(p.name)}</div><div class="ps">${esc(p.specialty)}</div>`; | |
| d.title = 'A\u00f1adir al equipo'; | |
| d.addEventListener('click', () => { | |
| if (agents.some(a => a.name === p.name)) { setStatus(`${p.name} ya est\u00e1 en el equipo.`); return; } | |
| agents.push({ name: p.name, emoji: p.emoji, color: p.color, specialty: p.specialty, system: p.system, temp: 0.7, maxTokens: 256 }); | |
| lsSet(K.agents, agents); renderRoster(); | |
| setStatus(`${p.name} se ha unido al equipo (${agents.length} agentes).`); | |
| }); | |
| g.appendChild(d); | |
| }); | |
| } | |
| function renderTemplates() { | |
| const g = $('templates'); | |
| g.innerHTML = ''; | |
| TEMPLATES.forEach(t => { | |
| const d = document.createElement('div'); | |
| d.className = 'preset'; | |
| d.innerHTML = `<div class="pe">${t.emoji}</div><div class="pn">${esc(t.name)}</div><div class="ps">${MODES[t.mode].name} \u00b7 ${t.agents.length} agentes</div>`; | |
| d.title = 'Aplicar modo, equipo y tema'; | |
| d.addEventListener('click', () => { | |
| agents = t.agents.map(n => { | |
| const p = PRESETS.find(x => x.name === n); | |
| return p ? { name: p.name, emoji: p.emoji, color: p.color, specialty: p.specialty, system: p.system, temp: 0.7, maxTokens: 256 } : null; | |
| }).filter(Boolean); | |
| if (agents.length < 2) agents = DEFAULT_AGENTS.slice(); | |
| lsSet(K.agents, agents); renderRoster(); | |
| selectMode(t.mode); | |
| $('topic').value = t.topic; | |
| setStatus(`Plantilla «${t.name}» aplicada. Pulsa Iniciar cuando quieras.`); | |
| document.querySelector('nav.tabs button[data-tab="debate"]').click(); | |
| }); | |
| g.appendChild(d); | |
| }); | |
| } | |
| const agentModal = $('agent-modal'); | |
| let editingAgent = -1; | |
| function openAgentEditor(i) { | |
| editingAgent = i; | |
| const a = agents[i] || {}; | |
| $('agent-modal-title').textContent = i >= 0 ? 'Editar agente' : 'Nuevo agente'; | |
| $('agent-delete').style.display = i >= 0 ? 'inline-block' : 'none'; | |
| $('agent-name').value = a.name || ''; | |
| $('agent-emoji').value = a.emoji || '\u{1F916}'; | |
| $('agent-color').value = /^#[0-9a-fA-F]{6}$/.test(a.color || '') ? a.color : '#2dd4bf'; | |
| $('agent-spec').value = a.specialty || ''; | |
| $('agent-system').value = a.system || ''; | |
| $('agent-temp').value = a.temp ?? 0.7; | |
| $('agent-maxtokens').value = a.maxTokens ?? 256; | |
| agentModal.classList.add('open'); | |
| $('agent-name').focus(); | |
| } | |
| function deleteAgent(i) { | |
| const a = agents[i]; | |
| if (!a) return; | |
| if (agents.length <= 2) { alert('Se necesitan al menos 2 agentes.'); return; } | |
| if (!confirm(`\u00bfQuitar a ${a.name} del equipo?`)) return; | |
| agents.splice(i, 1); | |
| lsSet(K.agents, agents); renderRoster(); | |
| } | |
| $('add-agent').addEventListener('click', () => openAgentEditor(-1)); | |
| $('reset-agents').addEventListener('click', () => { | |
| if (!confirm('\u00bfVolver al equipo base de 3 agentes?')) return; | |
| agents = DEFAULT_AGENTS.slice(); lsSet(K.agents, agents); renderRoster(); | |
| }); | |
| $('agent-cancel').addEventListener('click', () => agentModal.classList.remove('open')); | |
| agentModal.addEventListener('click', e => { if (e.target === agentModal) agentModal.classList.remove('open'); }); | |
| $('agent-delete').addEventListener('click', () => { deleteAgent(editingAgent); agentModal.classList.remove('open'); }); | |
| $('agent-save').addEventListener('click', () => { | |
| const name = $('agent-name').value.trim(); | |
| if (!name) { alert('El nombre no puede estar vac\u00edo.'); return; } | |
| const system = $('agent-system').value.trim(); | |
| if (!system) { alert('Describe la personalidad del agente.'); return; } | |
| const data = { | |
| name, system, | |
| emoji: $('agent-emoji').value.trim() || '\u{1F916}', | |
| color: $('agent-color').value, | |
| specialty: $('agent-spec').value.trim() || 'Generalista', | |
| temp: Math.min(1.5, Math.max(0, parseFloat($('agent-temp').value) || 0.7)), | |
| maxTokens: Math.min(1024, Math.max(64, parseInt($('agent-maxtokens').value) || 256)), | |
| }; | |
| if (editingAgent >= 0) agents[editingAgent] = data; else agents.push(data); | |
| lsSet(K.agents, agents); renderRoster(); | |
| agentModal.classList.remove('open'); | |
| }); | |
| /* ================= Modos y temas ================= */ | |
| function selectMode(m) { | |
| mode = m; | |
| document.querySelectorAll('.mode-card').forEach(c => c.classList.toggle('sel', c.dataset.mode === m)); | |
| } | |
| (function renderModes() { | |
| const g = $('modes'); | |
| Object.entries(MODES).forEach(([key, m]) => { | |
| const d = document.createElement('div'); | |
| d.className = 'mode-card' + (key === mode ? ' sel' : ''); | |
| d.dataset.mode = key; | |
| d.innerHTML = `<div class="me">${m.emoji}</div><div class="mn">${m.name}</div><div class="md">${m.desc}</div>`; | |
| d.addEventListener('click', () => selectMode(key)); | |
| g.appendChild(d); | |
| }); | |
| })(); | |
| (function fillSuggestions() { | |
| const sugg = $('topic-sugg'); | |
| const ph = document.createElement('option'); | |
| ph.value = ''; ph.textContent = '\u{1F3B2} Ideas y experimentos\u2026'; | |
| sugg.appendChild(ph); | |
| [...TOPIC_POOL].sort(() => Math.random() - .5).slice(0, 10).forEach(t => { | |
| const o = document.createElement('option'); | |
| o.value = t; o.textContent = t.length > 60 ? t.slice(0, 57) + '\u2026' : t; | |
| sugg.appendChild(o); | |
| }); | |
| sugg.addEventListener('change', () => { | |
| if (sugg.value) { $('topic').value = sugg.value; $('topic').focus(); } | |
| sugg.selectedIndex = 0; | |
| }); | |
| })(); | |
| /* ================= Modelo ================= */ | |
| function engineBadge() { | |
| const el = $('st-engine'); | |
| el.textContent = 'wllama (WASM/CPU)'; | |
| } | |
| async function updateStorageStat() { | |
| try { | |
| const e = await navigator.storage.estimate(); | |
| if (e && e.quota) $('st-mem').textContent = `${((e.usage || 0) / 1048576).toFixed(0)} MB / ${(e.quota / 1073741824).toFixed(1)} GB`; | |
| } catch (err) {} | |
| } | |
| function setPill(state, txt) { | |
| const p = $('model-pill'); | |
| p.className = 'model-pill ' + state; | |
| $('model-pill-txt').textContent = txt; | |
| } | |
| async function loadModel(repo, file) { | |
| const url = CONFIG.modelUrl || `https://huggingface.co/${repo}/resolve/main/${file}`; | |
| $('start-btn').disabled = true; | |
| setProgress(0); | |
| setPill('', 'cargando…'); | |
| setStatus(`Descargando ${file} (ctx ${CONFIG.nCtx})\u2026`); | |
| const t0 = performance.now(); | |
| try { | |
| if (wllama) await wllama.exit(); | |
| wllama = new Wllama({ | |
| 'default': 'https://cdn.jsdelivr.net/npm/@wllama/wllama@3.5.1/esm/wasm/wllama.wasm', | |
| }, { parallelDownloads: 5 }); | |
| await wllama.loadModelFromUrl(url, { | |
| n_gpu_layers: 999, | |
| n_ctx: CONFIG.nCtx, | |
| n_batch: 512, | |
| n_threads: Math.max(1, Math.min(8, navigator.hardwareConcurrency || 4)), | |
| progressCallback: ({ loaded, total }) => { | |
| if (total > 0) { | |
| modelBytes = total; | |
| const pct = Math.round((loaded / total) * 100); | |
| setProgress(pct); | |
| setStatus(`Descargando\u2026 ${pct}% (${(loaded / 1048576).toFixed(0)} MB)`); | |
| } | |
| }, | |
| }); | |
| modelLoadMs = performance.now() - t0; | |
| $('st-modelmem').textContent = modelBytes ? (modelBytes / 1048576).toFixed(0) + ' MB' : '—'; | |
| setProgress(100); | |
| setPill('ready', file.replace('.gguf', '').slice(0, 34)); | |
| setStatus(`Modelo listo en ${(modelLoadMs / 1000).toFixed(0)} s. ${agents.length} agentes preparados.`); | |
| $('start-btn').disabled = false; | |
| $('start-btn').textContent = 'Iniciar debate'; | |
| updateStorageStat(); | |
| } catch (e) { | |
| console.error(e); | |
| setPill('error', 'error de carga'); | |
| setStatus('Error al cargar el modelo'); | |
| addSysNote('No se pudo cargar el modelo: ' + (e?.message || e) + | |
| '. Si la descarga se interrumpi\u00f3 o falta espacio, prueba el bot\u00f3n de limpieza o un modelo m\u00e1s peque\u00f1o en Ajustes.'); | |
| const b = document.createElement('button'); | |
| b.className = 'btn small'; b.style.marginTop = '8px'; | |
| b.textContent = 'Limpiar cach\u00e9 y reintentar'; | |
| b.addEventListener('click', async () => { | |
| b.disabled = true; b.textContent = 'Limpiando\u2026'; | |
| try { | |
| if ('caches' in window) for (const k of await caches.keys()) await caches.delete(k); | |
| if (indexedDB.databases) for (const db of await indexedDB.databases()) | |
| await new Promise(r => { const q = indexedDB.deleteDatabase(db.name); q.onsuccess = q.onerror = q.onblocked = r; }); | |
| if (navigator.storage?.getDirectory) { | |
| const dir = await navigator.storage.getDirectory().catch(() => null); | |
| if (dir) for await (const k of dir.keys()) await dir.removeEntry(k, { recursive: true }).catch(() => {}); | |
| } | |
| } catch (_) {} | |
| loadModel(repo, file); | |
| }); | |
| $('chat').appendChild(b); | |
| } | |
| } | |
| /* ================= Chat UI y estad\u00edsticas ================= */ | |
| const chatEl = $('chat'); | |
| function addMsg(agent, opts = {}) { | |
| const d = document.createElement('div'); | |
| d.className = 'msg' + (opts.isUser ? ' user' : '') + (opts.kind === 'devil' ? ' devil' : ''); | |
| const content = document.createElement('div'); | |
| content.className = 'content'; | |
| const who = document.createElement('div'); | |
| who.className = 'who'; | |
| const body = document.createElement('div'); | |
| body.className = 'body'; | |
| const meta = document.createElement('div'); | |
| meta.className = 'meta'; | |
| if (opts.isUser) { who.textContent = 'T\u00fa'; who.style.color = 'var(--accent)'; } | |
| else { | |
| const av = document.createElement('div'); | |
| av.className = 'avatar'; | |
| av.style.background = avatarBg(agent.color || '#2dd4bf'); | |
| av.style.boxShadow = '0 0 8px ' + (agent.color || '#2dd4bf') + '55'; | |
| av.textContent = agent.emoji || '\u{1F916}'; | |
| d.appendChild(av); | |
| who.textContent = agent.name; | |
| who.style.color = agent.color || 'var(--accent)'; | |
| } | |
| if (opts.role) { | |
| const rb = document.createElement('span'); | |
| rb.className = 'badge role'; | |
| rb.textContent = opts.role; | |
| who.appendChild(rb); | |
| } | |
| content.appendChild(who); content.appendChild(body); content.appendChild(meta); | |
| d.appendChild(content); | |
| chatEl.appendChild(d); | |
| chatEl.scrollTop = chatEl.scrollHeight; | |
| return { el: d, body, meta }; | |
| } | |
| function addSysNote(text) { | |
| const d = document.createElement('div'); | |
| d.className = 'msg system-note'; | |
| d.innerHTML = `<div class="content"><div class="body">${esc(text)}</div></div>`; | |
| chatEl.appendChild(d); | |
| chatEl.scrollTop = chatEl.scrollHeight; | |
| return d; | |
| } | |
| function bumpStats(name, tokens, ms) { | |
| stats.tokens[name] = (stats.tokens[name] || 0) + tokens; | |
| stats.turns[name] = (stats.turns[name] || 0) + 1; | |
| if (ms > 300 && tokens > 2) stats.speeds.push(tokens / (ms / 1000)); | |
| if (stats.speeds.length > 30) stats.speeds.shift(); | |
| $('st-turns').textContent = Object.values(stats.turns).reduce((a, b) => a + b, 0); | |
| $('st-tokens').textContent = Object.values(stats.tokens).reduce((a, b) => a + b, 0); | |
| const last = stats.speeds[stats.speeds.length - 1]; | |
| const avg = stats.speeds.length ? stats.speeds.reduce((a, b) => a + b, 0) / stats.speeds.length : 0; | |
| $('st-speed').textContent = stats.speeds.length ? `${last.toFixed(1)} / ${avg.toFixed(1)} tok/s` : '—'; | |
| $('st-ctx').textContent = '~' + Math.round(transcriptText(1000000).length / 4) + ' / ' + CONFIG.nCtx + ' tok'; | |
| const maxTok = Math.max(1, ...Object.values(stats.tokens)); | |
| const box = $('st-agents'); | |
| box.innerHTML = ''; | |
| Object.keys(stats.turns).forEach(n => { | |
| const a = agents.find(x => x.name === n); | |
| const color = a ? a.color : 'var(--accent)'; | |
| const row = document.createElement('div'); | |
| row.className = 'agent-stat'; | |
| row.innerHTML = `<div class="avatar" style="background:${avatarBg(color || '#2dd4bf')}">${a ? esc(a.emoji) : '🧑'}</div>` + | |
| `<div class="nm">${esc(n)}</div><div class="bar"><div style="width:${(stats.tokens[n] / maxTok) * 100}%;background:${color}"></div></div>` + | |
| `<div class="tk">${stats.turns[n]} turnos \u00b7 ${stats.tokens[n]} tok</div>`; | |
| box.appendChild(row); | |
| }); | |
| } | |
| /* ================= Motor de generaci\u00f3n ================= */ | |
| const RULES = 'Participas en un laboratorio de razonamiento entre varios agentes. ' + | |
| 'Responde SOLO con tu intervenci\u00f3n: 2-4 frases directas, en el idioma del tema del debate (espa\u00f1ol si el tema est\u00e1 en espa\u00f1ol). ' + | |
| 'No escribas tu nombre ni prefijos como "Nombre:". No repitas lo ya dicho; reacciona a lo anterior. ' + | |
| 'Si necesitas que otro agente concreto revise un punto, termina con una linea "SOLICITO REVISION: Nombre - motivo" (maximo una por debate). ' + | |
| 'Si cambias de opini\u00f3n, empieza con "Cambio de postura:". ' + | |
| 'Si necesitas que otro agente compruebe un dato o razonamiento, escribe al final "SOLICITO REVISION: <qu\u00e9>".'; | |
| function transcriptText(maxChars) { | |
| const lines = transcript.map(m => `${m.name || 'Usuario'}${m.role ? ' [' + m.role + ']' : ''}: ${m.text}`); | |
| let out = lines.join('\n\n'); | |
| let dropped = 0; | |
| while (out.length > maxChars && lines.length > 3) { lines.splice(1, 1); dropped++; out = lines.join('\n\n'); } | |
| if (dropped > 0) out = '(se han resumido ' + dropped + ' intervenciones antiguas por l\u00edmite de contexto)\n\n' + out; | |
| return out; | |
| } | |
| function memoryContext() { | |
| if (!$('mem-inject').checked) return ''; | |
| const mem = lsGet(K.memory, []); | |
| if (!mem.length) return ''; | |
| const items = mem.slice(0, 5).map(m => `- Sobre «${m.topic}»: ${m.conclusion}`).join('\n'); | |
| return 'Conclusiones de debates anteriores del laboratorio:\n' + items + '\n\n'; | |
| } | |
| async function llmCall(messages, maxTokens, temperature, onToken) { | |
| const t0 = performance.now(); | |
| let answer = '', reasoning = '', count = 0; | |
| const stream = await wllama.createChatCompletion({ | |
| messages, max_tokens: maxTokens, temperature, stream: true, | |
| }); | |
| for await (const chunk of stream) { | |
| if (stopRequested) break; | |
| const delta = chunk.choices?.[0]?.delta || {}; | |
| const tk = delta.content || ''; | |
| const rs = delta.reasoning_content || ''; | |
| if (rs) { reasoning += rs; if (onToken) onToken('', reasoning); } | |
| if (tk) { answer += tk; count++; if (onToken) onToken(answer, reasoning); } | |
| } | |
| const ms = performance.now() - t0; | |
| return { answer, reasoning, tokens: count, ms, stopped: stopRequested }; | |
| } | |
| async function agentTurn(agent, role, instr) { | |
| const view = transcriptText(CONFIG.economy ? 4000 : 9000); | |
| const messages = [ | |
| { role: 'system', content: agent.system + (role ? ` Tu rol en esta fase: ${role}.` : '') + ' ' + RULES }, | |
| { role: 'user', content: | |
| memoryContext() + | |
| `Tema del debate: ${topic}\nModo: ${MODES[mode].name}.\n\n` + | |
| (view ? `Debate hasta ahora:\n${view}\n\n` : 'A\u00fan no hay intervenciones.\n\n') + | |
| `Ahora hablas t\u00fa, ${agent.name}. ${instr}` }, | |
| ]; | |
| const { el, body, meta } = addMsg(agent, { role }); | |
| el.classList.add('streaming'); | |
| setStatus(`${agent.name} (${role || 'agente'}) est\u00e1 razonando\u2026`); | |
| let think = null; | |
| try { | |
| const r = await llmCall(messages, agent.maxTokens || CONFIG.maxTokens, agent.temp ?? CONFIG.temperature, | |
| (ans, rs) => { | |
| if (rs && !think) { | |
| think = document.createElement('details'); | |
| think.className = 'think'; | |
| think.innerHTML = '<summary>Pensamiento</summary><div class="t"></div>'; | |
| body.parentNode.insertBefore(think, body); | |
| } | |
| if (rs && think) think.querySelector('.t').textContent = rs; | |
| if (ans) body.textContent = ans; | |
| chatEl.scrollTop = chatEl.scrollHeight; | |
| }); | |
| el.classList.remove('streaming'); | |
| if (r.stopped) { el.remove(); return false; } | |
| let answer = r.answer.replace(/^\s*(?:\*\*)?[A-Za-z\u00c0-\u024f]+:\s*/, '').trim(); | |
| let reviewReq = null, reviewTarget = null; | |
| const mRev = /SOLICITO REVISION:\s*(.+?)$/im.exec(answer); | |
| if (mRev) { | |
| let req = mRev[1].trim(); | |
| answer = answer.replace(/SOLICITO REVISION:[\s\S]*$/im, '').trim(); | |
| const mName = /^([A-Za-z\u00c0-\u00ff][\w\u00c0-\u00ff]*)\s*[-\u2014:]\s*(.+)$/.exec(req); | |
| if (mName) { | |
| const t = agents.find(a => a.name.toLowerCase() === mName[1].toLowerCase() && a.name !== agent.name); | |
| if (t) { reviewTarget = t; req = mName[2].trim(); } | |
| } | |
| const echoish = /tema propuesto|debate hasta ahora/i.test(req) || (topic && req.toLowerCase().includes(topic.toLowerCase().slice(0, 30))); | |
| if (req.length >= 12 && !echoish) reviewReq = req.slice(0, 200); | |
| } | |
| if (!answer) { | |
| el.remove(); | |
| if (reviewReq && (stats.reviews || 0) < 2) { | |
| stats.reviews = (stats.reviews || 0) + 1; | |
| const other = reviewTarget || agents.find(a => a.name !== agent.name); | |
| if (other) { | |
| addSysNote(`${agent.name} pidi\u00f3 revisi\u00f3n a ${other.name}: ${reviewReq}`); | |
| await agentTurn(other, 'Revisor', `${agent.name} pidi\u00f3 que comprobaras esto: \u00ab${reviewReq}\u00bb. Revisa el razonamiento y responde si es correcto.`); | |
| } | |
| } | |
| setStatus('Listo'); | |
| return true; | |
| } | |
| const changed = /^cambio de postura/i.test(answer); | |
| body.innerHTML = (typeof marked !== 'undefined') ? marked.parse(answer) : esc(answer).replace(/\n/g, '<br>'); | |
| if (changed) { | |
| const c = document.createElement('span'); | |
| c.className = 'chip-change'; c.textContent = '\u{1F504} cambio de postura'; | |
| body.parentNode.querySelector('.who').appendChild(c); | |
| } | |
| meta.textContent = `${r.tokens} tokens \u00b7 ${(r.tokens / (r.ms / 1000)).toFixed(1)} tok/s`; | |
| transcript.push({ name: agent.name, role, text: answer, round: resume.round, tokens: r.tokens, ms: r.ms, changed }); | |
| bumpStats(agent.name, r.tokens, r.ms); | |
| if (reviewReq && (stats.reviews || 0) < 2) { | |
| stats.reviews = (stats.reviews || 0) + 1; | |
| const other = reviewTarget || agents.find(a => a.name !== agent.name); | |
| if (other) { | |
| addSysNote(`${agent.name} pidi\u00f3 revisi\u00f3n a ${other.name}: ${reviewReq}`); | |
| await agentTurn(other, 'Revisor', `${agent.name} pidi\u00f3 que comprobaras esto: «${reviewReq}». Revisa el razonamiento y responde si es correcto.`); | |
| } | |
| } | |
| return true; | |
| } catch (e) { | |
| console.error(e); | |
| el.classList.remove('streaming'); | |
| el.classList.add('err'); | |
| body.textContent = 'Error: ' + (e?.message || e); | |
| return false; | |
| } | |
| } | |
| /* ================= Orquestaci\u00f3n por modo ================= */ | |
| function buildSteps(m, round, lastRound) { | |
| const n = agents.length; | |
| const steps = []; | |
| const push = (idx, role, instr) => steps.push({ idx, role, instr }); | |
| if (m === 'adversarial') { | |
| const roles = [ | |
| ['Proponente', 'Exp\u00f3n o refuerza tu posici\u00f3n con un argumento concreto y defendible.'], | |
| ['Atacante', 'Encuentra el punto m\u00e1s d\u00e9bil del argumento anterior y at\u00e1calo con precisi\u00f3n.'], | |
| ['Defensor', 'Defiende la posici\u00f3n atacada: corrige, matiza o reconoce el fallo y mejora el argumento.'], | |
| ]; | |
| for (let i = 0; i < n; i++) { | |
| const [role, instr] = roles[(i + round - 1) % 3]; | |
| push(i, role, instr); | |
| } | |
| } else if (m === 'consejo') { | |
| for (let i = 0; i < n; i++) | |
| push(i, agents[i].specialty || 'Consejero', 'Desde tu perfil, aporta tu an\u00e1lisis para alcanzar una decisi\u00f3n conjunta.'); | |
| const s = (round - 1) % n; | |
| push(s, 'S\u00edntesis', 'Sintetiza el consejo: resume acuerdos y desacuerdos y prop\u00f3n una decisi\u00f3n conjunta.'); | |
| } else if (m === 'juicio') { | |
| const jr = ['Fiscal', 'Defensa', 'Juez']; | |
| for (let i = 0; i < n; i++) { | |
| if (i % 3 === 0) push(i, 'Fiscal', 'Como fiscal, presenta o refuerza los cargos con argumentos y evidencias.'); | |
| else if (i % 3 === 1) push(i, 'Defensa', 'Como defensa, rebate los cargos y protege tu posici\u00f3n.'); | |
| else push(i, 'Perito', 'Como perito imparcial, aporta valoraci\u00f3n t\u00e9cnica sobre lo dicho por ambas partes.'); | |
| } | |
| if (lastRound) push((n - 1), 'Juez', 'Como juez, valora las partes y emite un veredicto razonado. Empieza con "VEREDICTO:".'); | |
| } else if (m === 'investigacion') { | |
| for (let i = 0; i < n; i++) { | |
| if (round === 1) push(i, 'Hip\u00f3tesis', 'Formula tu hip\u00f3tesis sobre el tema y justif\u00edcala brevemente.'); | |
| else if (lastRound) push(i, 'Experimento', 'Dise\u00f1a un experimento o prueba concreta para comprobar las conclusiones del debate.'); | |
| else push(i, 'Contraprueba', 'Busca contradicciones y lagunas en las hip\u00f3tesis de los dem\u00e1s.'); | |
| } | |
| } else if (m === 'experimentos') { | |
| for (let i = 0; i < n; i++) { | |
| if (round === 1) push(i, 'Escenario', 'Desarrolla tu escenario: analiza las consecuencias de la situaci\u00f3n hipot\u00e9tica, con una cadena de efectos concreta y plazos.'); | |
| else if (lastRound) push(i, 'Predicci\u00f3n', 'Emite tu predicci\u00f3n final: qu\u00e9 ocurrir\u00eda, con qu\u00e9 confianza y qu\u00e9 se\u00f1al observable lo confirmar\u00eda.'); | |
| else push(i, 'Contraste', 'Contrasta tu escenario con los de los dem\u00e1s: se\u00f1ala qu\u00e9 predicciones divergen, por qu\u00e9, y ajusta o defiende la tuya.'); | |
| } | |
| } else if (m === 'resolucion') { | |
| for (let i = 0; i < n; i++) { | |
| if (round === 1) push(i, 'Propuesta', 'Prop\u00f3n tu soluci\u00f3n al problema, distinta de la de los dem\u00e1s.'); | |
| else if (lastRound) push(i, 'Comparaci\u00f3n', 'Compara las soluciones sobre la mesa, combina lo mejor y di cu\u00e1l es la mejor y por qu\u00e9.'); | |
| else push(i, 'Comparaci\u00f3n', 'Compara las soluciones propuestas, combina sus puntos fuertes y mejora la tuya.'); | |
| } | |
| } | |
| return steps; | |
| } | |
| async function runDebate() { | |
| running = true; | |
| stopRequested = false; | |
| $('start-btn').classList.add('hidden'); | |
| $('stop-btn').classList.remove('hidden'); | |
| $('topic').disabled = true; | |
| if (!stats.startTs) stats.startTs = Date.now(); | |
| const timer = setInterval(() => { if (stats.startTs) $('st-time').textContent = fmtTime(Date.now() - stats.startTs); }, 1000); | |
| try { | |
| for (let r = resume.round; r <= CONFIG.rounds && !stopRequested; r++) { | |
| resume.round = r; | |
| $('st-round').textContent = `${r}/${CONFIG.rounds}`; | |
| setStatus(`Ronda ${r}/${CONFIG.rounds} \u00b7 ${MODES[mode].name}`); | |
| const steps = (r === resume.round && resume.steps) ? resume.steps : buildSteps(mode, r, r === CONFIG.rounds); | |
| const startIdx = (r === resume.round) ? resume.stepIdx : 0; | |
| for (let s = startIdx; s < steps.length; s++) { | |
| if (stopRequested) { resume = { round: r, stepIdx: s, steps }; break; } | |
| const ok = await agentTurn(agents[steps[s].idx], steps[s].role, steps[s].instr); | |
| if (!ok) { if (stopRequested) resume = { round: r, stepIdx: s, steps }; break; } | |
| } | |
| if (!stopRequested) resume = { round: r + 1, stepIdx: 0, steps: null }; | |
| else break; | |
| } | |
| } finally { | |
| clearInterval(timer); | |
| running = false; | |
| $('stop-btn').classList.add('hidden'); | |
| $('start-btn').classList.remove('hidden'); | |
| $('start-btn').disabled = false; | |
| $('topic').disabled = false; | |
| if (stopRequested) { | |
| $('start-btn').textContent = 'Continuar debate'; | |
| setStatus('Pausado. Puedes continuar, intervenir o cambiar de tema.'); | |
| } else { | |
| debateFinished = true; | |
| $('start-btn').textContent = 'Nuevo debate'; | |
| $('devil-btn').disabled = false; | |
| $('devil-btn2').disabled = false; | |
| $('analyze-btn').disabled = false; | |
| setStatus('Debate terminado. Generando an\u00e1lisis\u2026'); | |
| await runAnalysis(true); | |
| } | |
| } | |
| } | |
| /* ================= An\u00e1lisis: consenso ================= */ | |
| async function llmSimple(system, user, maxTokens) { | |
| const r = await llmCall( | |
| [{ role: 'system', content: system }, { role: 'user', content: user }], | |
| maxTokens, 0.3, null); | |
| return r; | |
| } | |
| function analysisNote(text) { | |
| const d = document.createElement('div'); | |
| d.className = 'phase-note'; | |
| d.innerHTML = `<span class="spin">\u23F3</span><span>${esc(text)}</span>`; | |
| $('analysis-out').appendChild(d); | |
| return d; | |
| } | |
| function doneNote(d, text) { d.innerHTML = `<span>\u2705</span><span>${esc(text)}</span>`; } | |
| async function runConsensus() { | |
| const note = analysisNote('Buscando consenso din\u00e1mico\u2026'); | |
| const view = transcriptText(5000); | |
| const synth = await llmSimple( | |
| 'Eres un sintetizador neutral. Redacta conclusiones claras y breves.', | |
| `Tema: ${topic}\n\nDebate:\n${view}\n\nRedacta la conclusi\u00f3n final del debate en 3-5 frases, sin adornos.`, | |
| 220); | |
| const conclusion = synth.answer.trim() || 'Sin conclusi\u00f3n clara.'; | |
| const votes = []; | |
| for (const a of agents) { | |
| if (stopRequested) break; | |
| setStatus(`Votaci\u00f3n de consenso: ${a.name}\u2026`); | |
| const v = await llmSimple( | |
| a.system + ' Debes valorar una conclusi\u00f3n. Responde EXACTAMENTE en este formato:\nVOTO: SI\nRAZON: <una frase>', | |
| `Tema: ${topic}\n\nConclusi\u00f3n propuesta:\n${conclusion}\n\nDebate (resumen):\n${view.slice(-2500)}\n\n\u00bfEst\u00e1s de acuerdo con la conclusi\u00f3n? VOTA SI, PARCIAL o NO.`, | |
| 90); | |
| const m = /VOTO:\s*(SI|S\u00cd|PARCIAL|NO)/i.exec(v.answer); | |
| const razon = (/\nRAZON:\s*(.+)/i.exec(v.answer) || [])[1] || ''; | |
| votes.push({ name: a.name, vote: m ? m[1].toUpperCase().replace('\u00cd', 'I') : null, reason: razon.trim(), parsed: !!m }); | |
| } | |
| const pv = votes.filter(v => v.parsed); | |
| const si = pv.filter(v => v.vote === 'SI').length; | |
| const no = pv.filter(v => v.vote === 'NO').length; | |
| let status, cls, icon; | |
| if (!pv.length) { status = 'Consenso no disponible'; cls = ''; icon = '\u26AA'; } | |
| else if (si === pv.length) { status = 'Consenso alcanzado'; cls = 'ok'; icon = '\u{1F7E2}'; } | |
| else if (si + pv.filter(v => v.vote === 'PARCIAL').length >= Math.ceil(pv.length / 2) && no === 0) { status = 'Consenso parcial'; cls = 'partial'; icon = '\u{1F7E1}'; } | |
| else { status = 'Desacuerdo fundamentado'; cls = 'disagree'; icon = '\u{1F534}'; } | |
| doneNote(note, 'Consenso evaluado: ' + status); | |
| return { conclusion, votes, status, cls, icon, artifact: textArtifacts(conclusion, topic) }; | |
| } | |
| /* ================= An\u00e1lisis: evaluador ================= */ | |
| const CRITERIA = [ | |
| ['ARGUMENTOS', 'Calidad de argumentos'], | |
| ['COHERENCIA', 'Coherencia l\u00f3gica'], | |
| ['DETECCION', 'Detecci\u00f3n de errores'], | |
| ['EVIDENCIA', 'Evidencia y justificaci\u00f3n'], | |
| ['INCERTIDUMBRE', 'Reconoce incertidumbre'], | |
| ['CONCLUSION', 'Calidad de conclusi\u00f3n'], | |
| ]; | |
| // Un bloque de puntuaciones solo es usable si el modelo produjo valores plausibles: | |
| // descarta ecos de la rúbrica ("0, 10, 0, 10"), bloques casi vacíos y ceros totales. | |
| function blockUsable(b) { | |
| if (!b || b.invalid === true) return false; | |
| const present = Object.values(b.scores || {}).filter(v => v !== null && v !== undefined); | |
| if (present.length < 3) return false; | |
| if (present.every(v => v === 0)) return false; | |
| return true; | |
| } | |
| // Detecta artefactos de generación: eco del tema pegado al inicio ("ches autEl debate…") | |
| // o palabra de contenido repetida a muy corta distancia ("el peatón es el peatón"). | |
| function textArtifacts(text, topicStr) { | |
| if (!text) return false; | |
| const words = text.toLowerCase().match(/[a-z\u00e0-\u00fc]{5,}/g) || []; | |
| for (let i = 0; i < words.length - 1; i++) { | |
| if (words.slice(i + 1, i + 4).includes(words[i])) return true; | |
| } | |
| if (topicStr) { | |
| const t = topicStr.toLowerCase(); | |
| const head = text.slice(0, 24).toLowerCase(); | |
| for (let k = Math.min(head.length, 16); k >= 4; k--) { | |
| const idx = t.indexOf(head.slice(0, k)); | |
| if (idx < 0) continue; | |
| // Solo es eco si el prefijo engancha a media palabra dentro del tema ("…coches aut…" -> "ches aut"). | |
| if (idx > 0 && /[a-z\u00e0-\u00fc]/.test(t[idx - 1])) return true; | |
| break; | |
| } | |
| } | |
| return false; | |
| } | |
| async function runEvaluation() { | |
| const note = analysisNote('Evaluador analizando intervenciones\u2026'); | |
| const sysBase = 'Eres un evaluador de debates. Punt\u00faas con criterio y explicas cada puntuaci\u00f3n: premias rigor, evidencia y honestidad intelectual, no solo al m\u00e1s convincente.'; | |
| const fmt = | |
| 'Responde EXACTAMENTE con este formato (una l\u00ednea por criterio):\n' + | |
| 'AGENTE: <nombre>\nARGUMENTOS: <0-10>\nCOHERENCIA: <0-10>\nDETECCION: <0-10>\nEVIDENCIA: <0-10>\nINCERTIDUMBRE: <0-10>\nCONCLUSION: <0-10>\nCOMENTARIO: <una frase>\n\n' + | |
| 'Ejemplo (valores inventados):\nAGENTE: Demo\nARGUMENTOS: 7\nCOHERENCIA: 8\nDETECCION: 5\nEVIDENCIA: 6\nINCERTIDUMBRE: 7\nCONCLUSION: 6\nCOMENTARIO: Argumenta bien pero aporta poca evidencia.'; | |
| const parseBlocks = (answer) => { | |
| const out = []; | |
| const re = /AGENTE:\s*([^\n]+)\n([\s\S]*?)(?=\nAGENTE:|$)/g; | |
| let m; | |
| while ((m = re.exec(answer)) !== null) { | |
| const name = m[1].trim().replace(/\*+/g, ''); | |
| if (!agents.some(a => a.name.toLowerCase() === name.toLowerCase())) continue; | |
| const blk = m[2]; | |
| const scores = {}; | |
| CRITERIA.forEach(([key]) => { | |
| const mm = new RegExp(key + ':\\s*(\\d{1,2})').exec(blk); | |
| scores[key] = mm ? Math.min(10, parseInt(mm[1])) : null; | |
| }); | |
| const comment = (/COMENTARIO:\s*([^\n]+)/.exec(blk) || [])[1] || ''; | |
| const present = Object.values(scores).filter(v => v !== null); | |
| const total = present.length ? Math.round((present.reduce((a, b) => a + b, 0) / present.length) * 10) : null; | |
| let multi = 0; | |
| CRITERIA.forEach(([key]) => { | |
| const lm = new RegExp(key + ':\\s*([^\\n]*)').exec(blk); | |
| if (lm && (lm[1].match(/\d+/g) || []).length > 1) multi++; | |
| }); | |
| out.push({ name, scores, comment: comment.trim(), total, invalid: multi >= 2 }); | |
| } | |
| return out; | |
| }; | |
| // Un bloque por agente: salidas cortas y estructuradas, m\u00e1s fiables en modelos peque\u00f1os | |
| const blocks = []; | |
| for (const a of agents) { | |
| const own = transcript.filter(t => t.name === a.name).map(t => `[${t.role || 'turno'}]: ${t.text}`).join('\n'); | |
| if (!own) continue; | |
| const ask = (viewChars) => llmSimple(sysBase, | |
| `Tema: ${topic}\n\nIntervenciones de ${a.name}:\n${own.slice(0, viewChars)}\n\n` + | |
| `Punt\u00faa SOLO a ${a.name} de 0 a 10 seg\u00fan sus intervenciones. ${fmt}`, 260); | |
| let r = await ask(1500); | |
| let got = parseBlocks(r.answer).filter(b => b.name.toLowerCase() === a.name.toLowerCase()); | |
| if (!got.some(blockUsable)) { | |
| r = await ask(700); | |
| got = parseBlocks(r.answer).filter(b => b.name.toLowerCase() === a.name.toLowerCase()); | |
| } | |
| if (got.length) blocks.push(got[0]); | |
| else blocks.push({ name: a.name, scores: {}, comment: '', total: null, invalid: true }); | |
| if (stopRequested) break; | |
| } | |
| // Relaciones y detecciones: llamada corta aparte; NINGUNA si no hay base clara en el texto | |
| const view = transcriptText(3000); | |
| const r2 = await llmSimple(sysBase, | |
| `Tema: ${topic}\n\nDebate:\n${view}\n\n` + | |
| 'Responde solo con estas l\u00edneas; escribe NINGUNA si no hay base clara en el texto:\n' + | |
| 'RELACIONES: <qui\u00e9n apoya o contradice a qui\u00e9n, ej: Ada apoya a Bruno; o NINGUNA>\n' + | |
| 'CONTRADICCIONES: <o NINGUNA>\nFALACIAS: <o NINGUNA>\nSIN_JUSTIFICAR: <o NINGUNA>', 220); | |
| const grab = k => { | |
| const mm = new RegExp(k + ':\\s*([\\s\\S]*?)(?=\\n(?:RELACIONES|CONTRADICCIONES|FALACIAS|SIN_JUSTIFICAR):|$)').exec(r2.answer); | |
| const v = mm ? mm[1].trim() : ''; | |
| return /^NINGUNA/i.test(v) ? '' : v; | |
| }; | |
| const relations = grab('RELACIONES'); | |
| // Descarta eco de formato y relaciones sueltas presentadas como detecci\u00f3n: | |
| // "Ada contradice a Bruno" no prueba contradicci\u00f3n, falacia ni afirmaci\u00f3n sin justificar. | |
| const cleanExtra = (v) => { | |
| if (!v) return ''; | |
| if (/(AGENTE|RELACIONES|CONTRADICCIONES|FALACIA\w*|SIN_JUSTIFICAR)\s*:/i.test(v)) return ''; | |
| if (/^\s*[A-Za-z\u00c0-\u00ff]+\s+(apoya|contradice)\s+a\s+[A-Za-z\u00c0-\u00ff]+\s*\.?\s*$/i.test(v)) return ''; | |
| return v; | |
| }; | |
| const extra = { | |
| contradicciones: cleanExtra(grab('CONTRADICCIONES')), | |
| falacias: cleanExtra(grab('FALACIAS')), | |
| sinJustificar: cleanExtra(grab('SIN_JUSTIFICAR')), | |
| }; | |
| const usable = blocks.filter(blockUsable); | |
| doneNote(note, usable.length ? `Evaluaci\u00f3n completada (${usable.length} agentes).` : 'Evaluaci\u00f3n no disponible: salida del modelo no utilizable.'); | |
| return { blocks, relations, extra, raw: r2.answer, unavailable: usable.length === 0 }; | |
| } | |
| /* ================= An\u00e1lisis: mapa de argumentos ================= */ | |
| async function runArgMap() { | |
| const note = analysisNote('Extrayendo mapa de argumentos\u2026'); | |
| const view = transcriptText(4500); | |
| const r = await llmSimple( | |
| 'Extraes la estructura de un debate. Responde EXACTAMENTE con este formato:\nTESIS: <frase>\nEVIDENCIA: <una l\u00ednea por evidencia, m\u00e1x 3>\nOBJECCION: <una l\u00ednea por objecci\u00f3n, m\u00e1x 3>\nCONCLUSION: <frase>', | |
| `Tema: ${topic}\n\nDebate:\n${view}`, 320); | |
| const lines = r.answer.split('\n').map(l => l.trim()).filter(Boolean); | |
| const map = { tesis: [], evid: [], obj: [], concl: [] }; | |
| let cur = null; | |
| for (const l of lines) { | |
| const mm = /^(TESIS|EVIDENCIA|OBJECCION|CONCLUSION):\s*(.+)$/.exec(l); | |
| if (mm) { | |
| cur = mm[1] === 'TESIS' ? 'tesis' : mm[1] === 'EVIDENCIA' ? 'evid' : mm[1] === 'OBJECCION' ? 'obj' : 'concl'; | |
| map[cur].push(mm[2].trim()); | |
| } else if (cur && map[cur].length < 4 && !/^(AGENTE|RELACIONES)/.test(l)) map[cur].push(l); | |
| } | |
| doneNote(note, 'Mapa de argumentos extra\u00eddo.'); | |
| return map; | |
| } | |
| /* ================= Devil's Advocate ================= */ | |
| async function runDevil() { | |
| if (!wllama || !analysis || !analysis.consensus) return; | |
| const devil = { name: "Devil's Advocate", emoji: '\u{1F47F}', color: '#f87171' }; | |
| document.querySelector('nav.tabs button[data-tab="debate"]').click(); | |
| addSysNote('Aparece el Devil\u2019s Advocate: su \u00fanica misi\u00f3n es demostrar que la conclusi\u00f3n podr\u00eda ser incorrecta. (Mismo modelo local, contexto separado.)'); | |
| const { el, body, meta } = addMsg(devil, { role: 'Abogado del diablo' }); | |
| el.classList.add('streaming'); | |
| setStatus('El Devil\u2019s Advocate prepara su ataque\u2026'); | |
| const view = transcriptText(4000); | |
| const messages = [ | |
| { role: 'system', content: 'Eres el Devil\u2019s Advocate: tu \u00fanica misi\u00f3n es intentar desmontar la conclusi\u00f3n final de un debate. Encuentra supuestos ocultos, se\u00f1ala argumentos d\u00e9biles y prop\u00f3n escenarios alternativos. 4-6 frases, en espa\u00f1ol, directas.' }, | |
| { role: 'user', content: `Tema: ${topic}\n\nConclusi\u00f3n del debate:\n${analysis.consensus.conclusion}\n\nDebate (extracto):\n${view}\n\nAtaca la conclusi\u00f3n.` }, | |
| ]; | |
| try { | |
| const r = await llmCall(messages, 320, 0.85, (ans) => { body.textContent = ans; chatEl.scrollTop = chatEl.scrollHeight; }); | |
| el.classList.remove('streaming'); | |
| const text = r.answer.trim(); | |
| body.innerHTML = (typeof marked !== 'undefined') ? marked.parse(text) : esc(text); | |
| meta.textContent = `${r.tokens} tokens \u00b7 ${(r.tokens / (r.ms / 1000)).toFixed(1)} tok/s`; | |
| transcript.push({ name: devil.name, role: 'Abogado del diablo', text, round: 'DA', tokens: r.tokens, ms: r.ms, kind: 'devil' }); | |
| analysis.devil = text; | |
| saveToLibrary(); | |
| setStatus('El Devil\u2019s Advocate ha hablado. \u00bfResiste la conclusi\u00f3n?'); | |
| } catch (e) { | |
| el.classList.remove('streaming'); el.classList.add('err'); | |
| body.textContent = 'Error: ' + (e?.message || e); | |
| } | |
| } | |
| /* ================= An\u00e1lisis: orquestaci\u00f3n y render ================= */ | |
| async function runAnalysis(auto) { | |
| if (!wllama || !transcript.length) return; | |
| const myToken = ++analysisToken; | |
| $('analyze-btn').disabled = true; | |
| $('analysis-empty').classList.add('hidden'); | |
| $('analysis-out').innerHTML = ''; | |
| document.querySelector('nav.tabs button[data-tab="analisis"]').click(); | |
| try { | |
| const consensus = await runConsensus(); | |
| const evaluation = await runEvaluation(); | |
| const argmap = await runArgMap(); | |
| if (myToken !== analysisToken) return; // debate reabierto o reiniciado durante el análisis | |
| analysis = { consensus, evaluation, argmap, devil: analysis?.devil || null, ts: Date.now() }; | |
| renderAnalysis(); | |
| saveToLibrary(); | |
| saveToMemory(consensus); | |
| updateRanking(evaluation); | |
| setStatus('An\u00e1lisis completado. Puedes invocar al Devil\u2019s Advocate.'); | |
| if (auto) await runDevil(); | |
| } catch (e) { | |
| console.error(e); | |
| addSysNote('Error durante el an\u00e1lisis: ' + (e?.message || e)); | |
| setStatus('An\u00e1lisis interrumpido.'); | |
| } finally { | |
| $('analyze-btn').disabled = false; | |
| } | |
| } | |
| function renderAnalysis() { | |
| if (!analysis) return; | |
| const out = $('analysis-out'); | |
| $('analysis-empty').classList.add('hidden'); | |
| const c = analysis.consensus; | |
| const e = analysis.evaluation; | |
| const am = analysis.argmap; | |
| let html = ''; | |
| const voteOk = v => v.parsed !== undefined ? v.parsed : !!(v.vote && v.reason); | |
| const noUsableVotes = Array.isArray(c.votes) && c.votes.length > 0 && !c.votes.some(voteOk); | |
| // --- Consenso --- | |
| html += `<div class="consensus-hero ${noUsableVotes ? '' : c.cls}"><div class="ci">${noUsableVotes ? '\u26AA' : c.icon}</div><div>` + | |
| `<div class="cs">${esc(noUsableVotes ? 'Consenso no disponible' : c.status)}</div>` + | |
| `<div class="muted">Conclusi\u00f3n: ${esc(c.conclusion)}</div>` + | |
| ((c.artifact ?? textArtifacts(c.conclusion, topic)) ? `<div class="muted" style="margin-top:4px">\u26A0\uFE0F La conclusi\u00f3n muestra artefactos de generaci\u00f3n (eco o repetici\u00f3n del modelo); interpr\u00e9tala con cautela.</div>` : '') + | |
| `</div></div>`; | |
| html += `<div class="panel" style="background:var(--panel2)"><h3>\u{1F5F3}\uFE0F Votaci\u00f3n de los agentes</h3><div class="vote-list">`; | |
| c.votes.forEach(v => { | |
| if (!voteOk(v)) { html += `<div class="vrow"><span class="vv" style="color:var(--muted)">—</span><span><b>${esc(v.name)}</b> — sin voto utilizable</span></div>`; return; } | |
| const cls = v.vote === 'SI' ? 'si' : v.vote === 'NO' ? 'no' : 'parcial'; | |
| html += `<div class="vrow"><span class="vv ${cls}">${v.vote}</span><span><b>${esc(v.name)}</b>${v.reason ? ' — ' + esc(v.reason) : ''}</span></div>`; | |
| }); | |
| html += '</div>'; | |
| if (!c.votes.some(voteOk)) { | |
| html += `<div class="muted" style="margin-top:8px">Los agentes no emitieron votos utilizables; el estado de consenso no es fiable y se muestra como no disponible.</div>`; | |
| } | |
| if (c.cls !== 'ok') { | |
| const reasons = c.votes.filter(v => voteOk(v) && v.vote !== 'SI' && v.reason); | |
| if (reasons.length) html += `<div class="muted" style="margin-top:8px"><b style="color:var(--text)">Por qu\u00e9 no hay acuerdo:</b> ` + | |
| reasons.map(v => `${esc(v.name)}: ${esc(v.reason)}`).join(' \u00b7 ') + '</div>'; | |
| } | |
| html += '</div>'; | |
| // --- Puntuaciones --- | |
| if (e && e.blocks.length) { | |
| const usableBlocks = e.blocks.filter(blockUsable); | |
| if (!usableBlocks.length) { | |
| html += `<h3 style="margin-top:16px;color:var(--accent);font-size:13px;letter-spacing:1px">EVALUACI\u00d3N DEL DEBATE</h3>` + | |
| `<div class="panel" style="background:var(--panel2)"><div class="muted" style="color:var(--text)">Evaluaci\u00f3n no disponible: el modelo no produjo puntuaciones utilizables (salida degenerada o incompleta). Se omiten tarjetas y ranking para no presentar ceros como medici\u00f3n. Prueba con un modelo m\u00e1s capaz en Ajustes.</div></div>`; | |
| } else { | |
| const omitted = e.blocks.length - usableBlocks.length; | |
| html += `<h3 style="margin-top:16px;color:var(--accent);font-size:13px;letter-spacing:1px">EVALUACI\u00d3N DEL DEBATE (orientativa)</h3>` + | |
| (omitted ? `<div class="muted" style="margin-bottom:6px">${omitted} agente(s) sin puntuaci\u00f3n utilizable; se omiten sus tarjetas.</div>` : '') + | |
| `<div class="score-grid">`; | |
| usableBlocks.sort((a, b) => (b.total ?? 0) - (a.total ?? 0)).forEach(b => { | |
| const a = agents.find(x => x.name.toLowerCase() === b.name.toLowerCase()); | |
| html += `<div class="scard"><div class="stop">` + | |
| `<div class="avatar" style="background:${avatarBg(a?.color || '#2dd4bf')}">${esc(a?.emoji || '\u{1F916}')}</div>` + | |
| `<div><div class="aname">${esc(b.name)}</div><div class="aspec">${esc(a?.specialty || '')}</div></div>` + | |
| `<div class="big">${b.total ?? '?'}<span style="font-size:13px;color:var(--muted)">/100</span></div></div><div class="crit">`; | |
| CRITERIA.forEach(([key, label]) => { | |
| const v = b.scores[key]; | |
| html += `<div class="crow"><span class="lb">${label}</span>` + | |
| `<span class="bar"><div style="width:${v !== null ? v * 10 : 0}%"></div></span>` + | |
| `<span class="vl">${v !== null ? v : '—'}</span></div>`; | |
| }); | |
| if (b.comment) html += `<div class="comment">\u00ab${esc(b.comment)}\u00bb</div>`; | |
| html += '</div></div>'; | |
| }); | |
| html += '</div>'; | |
| } | |
| const evalOk = e.unavailable === undefined ? e.blocks.some(blockUsable) : !e.unavailable; | |
| if (!evalOk) { | |
| html += `<div class="panel" style="background:var(--panel2);margin-top:10px"><div class="muted" style="color:var(--text)">Relaciones y detectores no disponibles: la salida del evaluador no fue utilizable; no se presentan coincidencias de texto como detecciones.</div></div>`; | |
| } | |
| if (evalOk && e.relations) { | |
| html += `<h3 style="margin-top:14px;color:var(--accent);font-size:13px;letter-spacing:1px">MAPA DE RELACIONES</h3><div class="relchips">`; | |
| e.relations.split(';').map(x => x.trim()).filter(Boolean).forEach(rel => { | |
| const cls = /contradice|ataca|rebate/i.test(rel) ? 'con' : 'sup'; | |
| html += `<span class="relchip ${cls}">${esc(rel)}</span>`; | |
| }); | |
| html += '</div>'; | |
| } | |
| const extras = []; | |
| if (evalOk && e.extra.contradicciones) extras.push(['\u{1F500} Contradicciones', e.extra.contradicciones]); | |
| if (evalOk && e.extra.falacias) extras.push(['\u26A0\uFE0F Falacias l\u00f3gicas', e.extra.falacias]); | |
| if (evalOk && e.extra.sinJustificar) extras.push(['\u2753 Afirmaciones sin justificar', e.extra.sinJustificar]); | |
| if (extras.length) { | |
| html += `<h3 style="margin-top:14px;color:var(--accent);font-size:13px;letter-spacing:1px">DETECTORES</h3>`; | |
| extras.forEach(([t, v]) => { | |
| html += `<div class="panel" style="background:var(--panel2);margin-top:8px"><h3>${t}</h3><div class="muted" style="color:var(--text)">${esc(v).replace(/\n/g, '<br>')}</div></div>`; | |
| }); | |
| } | |
| } | |
| // --- Veredicto (modo juicio) --- | |
| if (mode === 'juicio') { | |
| const vt = [...transcript].reverse().find(t => /^\s*VEREDICTO:/i.test(t.text || '')); | |
| if (vt) { | |
| html += `<h3 style="margin-top:16px;color:var(--accent);font-size:13px;letter-spacing:1px">\u2696\uFE0F VEREDICTO DEL JUEZ</h3>` + | |
| `<div class="panel" style="background:var(--panel2)"><b>${esc(vt.name)}</b><div class="muted" style="color:var(--text);margin-top:4px">${esc(vt.text.replace(/^\s*VEREDICTO:\s*/i, '')).replace(/\n/g, '<br>')}</div>` + | |
| (textArtifacts(vt.text, topic) ? `<div class="muted" style="margin-top:4px">\u26A0\uFE0F Texto con artefactos de generaci\u00f3n (eco o repetici\u00f3n); interpr\u00e9talo con cautela.</div>` : '') + | |
| `<div class="muted" style="margin-top:4px">El juez lo interpreta el mismo modelo local que las partes; no es un juez independiente.</div></div>`; | |
| } | |
| } | |
| // --- Mapa de argumentos --- | |
| if (am && (am.tesis.length || am.evid.length || am.obj.length || am.concl.length)) { | |
| html += `<h3 style="margin-top:16px;color:var(--accent);font-size:13px;letter-spacing:1px">MAPA DE ARGUMENTOS</h3><div class="argmap">`; | |
| const col = (cls, title, items) => { | |
| let h = `<div class="argcol ${cls}"><h4>${title}</h4>`; | |
| items.slice(0, 4).forEach(i => { h += `<div class="argnode">${esc(i)}</div>`; }); | |
| return h + '</div>'; | |
| }; | |
| html += col('tesis', 'Tesis', am.tesis) + col('evid', 'Evidencias', am.evid) + | |
| col('obj', 'Objeciones', am.obj) + col('concl', 'Conclusi\u00f3n', am.concl); | |
| html += '</div>'; | |
| } | |
| // --- Evoluci\u00f3n de posturas --- | |
| html += `<h3 style="margin-top:16px;color:var(--accent);font-size:13px;letter-spacing:1px">EVOLUCI\u00d3N DE POSTURAS</h3><div class="timeline">`; | |
| for (let r = 1; r <= CONFIG.rounds; r++) { | |
| const items = transcript.filter(t => t.round === r); | |
| if (!items.length) continue; | |
| html += `<div class="tl-round"><h4>Ronda ${r}</h4>`; | |
| items.forEach(t => { | |
| html += `<div class="tl-item"><span class="who">${esc(t.name)}${t.changed ? ' \u{1F504}' : ''}</span>` + | |
| `<span class="what">${esc(t.text.slice(0, 140))}${t.text.length > 140 ? '\u2026' : ''}</span></div>`; | |
| }); | |
| html += '</div>'; | |
| } | |
| html += '</div>'; | |
| if (analysis.devil) { | |
| html += `<h3 style="margin-top:16px;color:var(--red);font-size:13px;letter-spacing:1px">\u{1F47F} DEVIL'S ADVOCATE</h3>` + | |
| `<div class="panel" style="background:#f8717110;border-color:var(--red)"><div class="muted" style="color:var(--text)">${esc(analysis.devil).replace(/\n/g, '<br>')}</div>` + | |
| (textArtifacts(analysis.devil, topic) ? `<div class="muted" style="margin-top:4px">\u26A0\uFE0F Texto con artefactos de generaci\u00f3n (eco o repetici\u00f3n); interpr\u00e9talo con cautela.</div>` : '') + | |
| `</div>`; | |
| } | |
| out.innerHTML = html; | |
| } | |
| /* ================= Persistencia ================= */ | |
| function saveToLibrary() { | |
| const lib = lsGet(K.library, []); | |
| const rec = { | |
| id: currentLibId || Date.now(), topic, mode, modeName: MODES[mode].name, ts: Date.now(), | |
| agents: agents.map(a => ({ name: a.name, emoji: a.emoji, color: a.color, specialty: a.specialty })), | |
| transcript, consensus: analysis.consensus, evaluation: analysis.evaluation, | |
| argmap: analysis.argmap, devil: analysis.devil, | |
| stats: { tokens: stats.tokens, turns: stats.turns }, | |
| }; | |
| const i = lib.findIndex(x => x.id === rec.id); | |
| if (i >= 0) lib[i] = rec; else lib.unshift(rec); | |
| currentLibId = rec.id; | |
| lsSet(K.library, lib.slice(0, 25)); | |
| } | |
| function saveToMemory(consensus) { | |
| if (!consensus || !consensus.conclusion || consensus.artifact) return; | |
| const mem = lsGet(K.memory, []); | |
| mem.unshift({ topic, conclusion: consensus.conclusion, status: consensus.status, ts: Date.now() }); | |
| lsSet(K.memory, mem.slice(0, 12)); | |
| } | |
| function updateRanking(evaluation) { | |
| if (!evaluation || !evaluation.blocks || evaluation.unavailable) return; | |
| const rank = lsGet(K.ranking, {}); | |
| evaluation.blocks.forEach(b => { | |
| if (b.total === null || !blockUsable(b)) return; | |
| const r = rank[b.name] || { total: 0, n: 0 }; | |
| rank[b.name] = { total: r.total + b.total, n: r.n + 1 }; | |
| }); | |
| lsSet(K.ranking, rank); | |
| } | |
| /* ================= Conocimiento ================= */ | |
| $('mem-inject').checked = !!lsGet(K.meminject, false); | |
| $('mem-inject').addEventListener('change', () => lsSet(K.meminject, $('mem-inject').checked)); | |
| function renderMemory() { | |
| const mem = lsGet(K.memory, []); | |
| const el = $('mem-list'); | |
| el.innerHTML = mem.length ? '' : '<div class="muted">Sin conclusiones guardadas todav\u00eda.</div>'; | |
| mem.forEach((m, i) => { | |
| const d = document.createElement('div'); | |
| d.className = 'mem-item'; | |
| d.innerHTML = `<div class="mt">${esc(m.topic)}</div>` + | |
| `<div class="mm">${new Date(m.ts).toLocaleString('es-ES')} \u00b7 ${esc(m.status || '')}</div>` + | |
| `<div class="mc">${esc(m.conclusion)}</div>` + | |
| `<div class="act" style="margin-top:7px"><button class="btn danger small" data-i="${i}">Eliminar</button></div>`; | |
| el.appendChild(d); | |
| }); | |
| el.querySelectorAll('[data-i]').forEach(b => b.addEventListener('click', () => { | |
| const mem2 = lsGet(K.memory, []); mem2.splice(+b.dataset.i, 1); lsSet(K.memory, mem2); renderMemory(); | |
| })); | |
| } | |
| $('mem-clear').addEventListener('click', () => { | |
| if (confirm('\u00bfVaciar la memoria de debates?')) { lsSet(K.memory, []); renderMemory(); } | |
| }); | |
| function renderRanking() { | |
| const rank = lsGet(K.ranking, {}); | |
| const rows = Object.entries(rank).map(([name, r]) => ({ name, avg: r.total / r.n, n: r.n })) | |
| .sort((a, b) => b.avg - a.avg); | |
| const el = $('ranking-out'); | |
| if (!rows.length) { el.innerHTML = '<div class="muted">Sin puntuaciones acumuladas todav\u00eda.</div>'; return; } | |
| let html = '<table class="rank-table"><tr><th>#</th><th>Agente</th><th>Media</th><th>Debates</th></tr>'; | |
| rows.forEach((r, i) => { | |
| html += `<tr><td>${i + 1}</td><td>${esc(r.name)}</td><td class="num">${r.avg.toFixed(0)}/100</td><td class="num">${r.n}</td></tr>`; | |
| }); | |
| el.innerHTML = html + '</table>'; | |
| } | |
| /* ================= Historial / biblioteca ================= */ | |
| function renderLibrary(filter) { | |
| const lib = lsGet(K.library, []); | |
| const q = (filter ?? $('lib-search').value).trim().toLowerCase(); | |
| const el = $('lib-list'); | |
| el.innerHTML = ''; | |
| const items = lib.filter(it => !q || | |
| it.topic.toLowerCase().includes(q) || it.modeName.toLowerCase().includes(q) || | |
| it.agents.some(a => a.name.toLowerCase().includes(q))); | |
| if (!items.length) { el.innerHTML = '<div class="muted">No hay debates guardados. Se guardan autom\u00e1ticamente al terminar el an\u00e1lisis.</div>'; return; } | |
| items.forEach(it => { | |
| const d = document.createElement('div'); | |
| d.className = 'lib-item'; | |
| const status = it.consensus ? it.consensus.status : 'sin an\u00e1lisis'; | |
| d.innerHTML = `<div class="mt">${esc(it.topic)}</div>` + | |
| `<div class="mm">${MODES[it.mode]?.emoji || ''} ${esc(it.modeName)} \u00b7 ${new Date(it.ts).toLocaleString('es-ES')} \u00b7 ` + | |
| `${it.agents.map(a => esc(a.name)).join(', ')} \u00b7 ${esc(status)}</div>` + | |
| `<div class="actions">` + | |
| `<button class="btn small" data-open="${it.id}">Reabrir</button>` + | |
| `<button class="btn ghost small" data-replay="${it.id}">\u23EA Replay</button>` + | |
| `<button class="btn ghost small" data-md="${it.id}">Markdown</button>` + | |
| `<button class="btn ghost small" data-json="${it.id}">JSON</button>` + | |
| `<button class="btn ghost small" data-html="${it.id}">HTML</button>` + | |
| `<button class="btn danger small" data-del="${it.id}">Eliminar</button></div>`; | |
| el.appendChild(d); | |
| }); | |
| el.querySelectorAll('[data-open]').forEach(b => b.addEventListener('click', () => reopenDebate(+b.dataset.open))); | |
| el.querySelectorAll('[data-replay]').forEach(b => b.addEventListener('click', () => replayDebate(+b.dataset.replay))); | |
| el.querySelectorAll('[data-md]').forEach(b => b.addEventListener('click', () => exportDebate(+b.dataset.md, 'md'))); | |
| el.querySelectorAll('[data-json]').forEach(b => b.addEventListener('click', () => exportDebate(+b.dataset.json, 'json'))); | |
| el.querySelectorAll('[data-html]').forEach(b => b.addEventListener('click', () => exportDebate(+b.dataset.html, 'html'))); | |
| el.querySelectorAll('[data-del]').forEach(b => b.addEventListener('click', () => { | |
| if (!confirm('\u00bfEliminar este debate de la biblioteca?')) return; | |
| lsSet(K.library, lsGet(K.library, []).filter(x => x.id !== +b.dataset.del)); | |
| renderLibrary(); | |
| })); | |
| } | |
| $('lib-search').addEventListener('input', () => renderLibrary()); | |
| $('lib-clear').addEventListener('click', () => { | |
| if (confirm('\u00bfBorrar toda la biblioteca de debates?')) { lsSet(K.library, []); renderLibrary(); } | |
| }); | |
| function reopenDebate(id) { | |
| const it = lsGet(K.library, []).find(x => x.id === id); | |
| if (!it) return; | |
| if (running) { | |
| stopRequested = true; | |
| setStatus('Pausando el debate actual antes de reabrir\u2026'); | |
| const waiter = setInterval(() => { if (!running) { clearInterval(waiter); reopenDebate(id); } }, 150); | |
| return; | |
| } | |
| document.querySelectorAll('.modal.open').forEach(m => m.classList.remove('open')); | |
| analysisToken++; | |
| currentLibId = it.id; | |
| topic = it.topic; mode = it.mode; | |
| $('topic').value = it.topic; | |
| selectMode(it.mode); | |
| transcript = it.transcript.slice(); | |
| chatEl.innerHTML = ''; | |
| transcript.forEach(t => renderHistoric(t)); | |
| resume = { round: CONFIG.rounds, stepIdx: 0, steps: null }; | |
| analysis = it.consensus ? { consensus: it.consensus, evaluation: it.evaluation, argmap: it.argmap, devil: it.devil, ts: it.ts } : null; | |
| debateFinished = true; | |
| $('devil-btn').disabled = false; $('devil-btn2').disabled = false; $('analyze-btn').disabled = false; | |
| $('start-btn').textContent = 'Continuar debate'; | |
| document.querySelector('nav.tabs button[data-tab="debate"]').click(); | |
| if (analysis) renderAnalysis(); | |
| setStatus(`Debate reabierto: ${it.agents.length} agentes, ${transcript.length} intervenciones. Puedes continuar.`); | |
| } | |
| function renderHistoric(t) { | |
| const a = agents.find(x => x.name === t.name) || | |
| (t.kind === 'devil' ? { name: t.name, emoji: '\u{1F47F}', color: '#f87171' } : | |
| { name: t.name || 'Usuario', emoji: '\u{1F9D1}', color: '#2dd4bf' }); | |
| const { body } = t.isUser ? addMsg(null, { isUser: true }) : addMsg(a, { role: t.role, kind: t.kind }); | |
| body.innerHTML = (typeof marked !== 'undefined') ? marked.parse(t.text) : esc(t.text); | |
| } | |
| let replayTimer = null; | |
| function replayDebate(id) { | |
| const it = lsGet(K.library, []).find(x => x.id === id); | |
| if (!it) return; | |
| if (running) { | |
| stopRequested = true; | |
| setStatus('Pausando el debate actual antes del replay\u2026'); | |
| const waiter = setInterval(() => { if (!running) { clearInterval(waiter); replayDebate(id); } }, 150); | |
| return; | |
| } | |
| document.querySelectorAll('.modal.open').forEach(m => m.classList.remove('open')); | |
| document.querySelector('nav.tabs button[data-tab="debate"]').click(); | |
| chatEl.innerHTML = ''; | |
| addSysNote(`\u23EA Replay: ${it.topic} (${it.transcript.length} turnos)`); | |
| let i = 0; | |
| clearInterval(replayTimer); | |
| replayTimer = setInterval(() => { | |
| if (i >= it.transcript.length) { clearInterval(replayTimer); addSysNote('Fin del replay.'); return; } | |
| const t = it.transcript[i++]; | |
| const a = (it.agents.find(x => x.name === t.name)) || | |
| { name: t.name || 'Usuario', emoji: t.kind === 'devil' ? '\u{1F47F}' : '\u{1F9D1}', color: t.kind === 'devil' ? '#f87171' : '#2dd4bf' }; | |
| const { body } = t.isUser ? addMsg(null, { isUser: true }) : addMsg(a, { role: t.role, kind: t.kind }); | |
| body.innerHTML = (typeof marked !== 'undefined') ? marked.parse(t.text) : esc(t.text); | |
| }, 1100); | |
| } | |
| /* ================= Exportaci\u00f3n ================= */ | |
| function download(name, content, type) { | |
| const a = document.createElement('a'); | |
| a.href = URL.createObjectURL(new Blob([content], { type })); | |
| a.download = name; | |
| a.click(); | |
| setTimeout(() => URL.revokeObjectURL(a.href), 5000); | |
| } | |
| function debateMarkdown(it) { | |
| let md = `# ${it.topic}\n\n**Modo:** ${it.modeName} · **Fecha:** ${new Date(it.ts).toLocaleString('es-ES')} · ` + | |
| `**Agentes:** ${it.agents.map(a => a.name).join(', ')}\n\n`; | |
| if (it.consensus) md += `## ${it.consensus.icon || ''} ${it.consensus.status}\n\n${it.consensus.conclusion}\n\n` + | |
| it.consensus.votes.map(v => `- **${v.name}: ${v.vote}**${v.reason ? ' — ' + v.reason : ''}`).join('\n') + '\n\n'; | |
| md += '## Transcripci\u00f3n\n\n'; | |
| it.transcript.forEach(t => { md += `**${t.name || 'Usuario'}**${t.role ? ' [' + t.role + ']' : ''}:\n${t.text}\n\n`; }); | |
| if (it.evaluation && it.evaluation.blocks) { | |
| md += '## Evaluaci\u00f3n (orientativa, mismo modelo)\n\n'; | |
| it.evaluation.blocks.forEach(b => { | |
| md += `### ${b.name}: ${b.total ?? '?'}/100\n`; | |
| CRITERIA.forEach(([k, l]) => { md += `- ${l}: ${b.scores[k] ?? '—'}/10\n`; }); | |
| if (b.comment) md += `> ${b.comment}\n`; | |
| md += '\n'; | |
| }); | |
| } | |
| if (it.devil) md += `## \u{1F47F} Devil's Advocate\n\n${it.devil}\n`; | |
| md += '\n---\nGenerado por Multi-Agent Lab (modelo local en el navegador, wllama/WASM). Evaluaciones orientativas, no objetivas.\n'; | |
| return md; | |
| } | |
| function debateHTML(it) { | |
| const md = debateMarkdown(it); | |
| const bodyHtml = (typeof marked !== 'undefined') ? marked.parse(md) : '<pre>' + esc(md) + '</pre>'; | |
| return `<!DOCTYPE html><html lang="es"><head><meta charset="utf-8"><title>${esc(it.topic)}</title>` + | |
| `<style>body{font-family:system-ui;max-width:760px;margin:30px auto;padding:0 16px;line-height:1.6;color:#111}</style></head>` + | |
| `<body>${bodyHtml}</body></html>`; | |
| } | |
| function exportDebate(id, fmt) { | |
| const it = lsGet(K.library, []).find(x => x.id === id); | |
| if (!it) return; | |
| const base = 'debate-' + new Date(it.ts).toISOString().slice(0, 10) + '-' + it.id; | |
| if (fmt === 'md') download(base + '.md', debateMarkdown(it), 'text/markdown'); | |
| else if (fmt === 'json') download(base + '.json', JSON.stringify(it, null, 2), 'application/json'); | |
| else if (fmt === 'html') download(base + '.html', debateHTML(it), 'text/html'); | |
| } | |
| /* ================= Controles principales ================= */ | |
| function startFresh(newTopic) { | |
| topic = newTopic; | |
| transcript = []; | |
| chatEl.innerHTML = ''; | |
| stats = { tokens: {}, turns: {}, speeds: [], startTs: 0, reviews: 0 }; | |
| ['st-turns', 'st-tokens'].forEach(id => $(id).textContent = '0'); | |
| $('st-speed').textContent = '—'; $('st-time').textContent = '0:00'; $('st-agents').innerHTML = ''; | |
| resume = { round: 1, stepIdx: 0, steps: null }; | |
| analysisToken++; | |
| analysis = null; | |
| currentLibId = null; | |
| debateFinished = false; | |
| $('analysis-out').innerHTML = ''; | |
| $('analysis-empty').classList.remove('hidden'); | |
| $('devil-btn').disabled = true; $('devil-btn2').disabled = true; $('analyze-btn').disabled = true; | |
| const m = addMsg(null, { isUser: true }); | |
| m.body.textContent = newTopic; | |
| transcript.push({ name: null, role: 'Tema', text: 'Tema propuesto: ' + newTopic, round: 0, isUser: true }); | |
| } | |
| $('start-btn').addEventListener('click', () => { | |
| if (!wllama || running) return; | |
| const newTopic = $('topic').value.trim(); | |
| if (newTopic && newTopic !== topic) startFresh(newTopic); | |
| else if (!topic) { $('topic').focus(); setStatus('Escribe un tema para debatir.'); return; } | |
| runDebate(); | |
| }); | |
| $('stop-btn').addEventListener('click', () => { stopRequested = true; setStatus('Pausando\u2026'); }); | |
| $('topic').addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); $('start-btn').click(); } }); | |
| function interject() { | |
| const txt = $('interject-txt').value.trim(); | |
| if (!txt) return; | |
| if (!topic) { setStatus('Primero inicia un debate.'); return; } | |
| const m = addMsg(null, { isUser: true }); | |
| m.body.textContent = txt; | |
| transcript.push({ name: null, role: 'Intervenci\u00f3n', text: txt, round: resume.round, isUser: true }); | |
| $('interject-txt').value = ''; | |
| if (!running && debateFinished === false && transcript.length > 1) { setStatus('Intervenci\u00f3n a\u00f1adida. Contin\u00faa el debate cuando quieras.'); } | |
| } | |
| $('interject-btn').addEventListener('click', interject); | |
| $('interject-txt').addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); interject(); } }); | |
| $('devil-btn').addEventListener('click', runDevil); | |
| $('devil-btn2').addEventListener('click', runDevil); | |
| $('analyze-btn').addEventListener('click', () => runAnalysis(false)); | |
| /* ================= Ajustes ================= */ | |
| const settingsModal = $('settings-modal'); | |
| $('settings-btn').addEventListener('click', () => { | |
| $('set-repo').value = CONFIG.repo; | |
| $('set-file').value = CONFIG.file; | |
| $('set-ctx').value = CONFIG.nCtx; | |
| $('set-maxtokens').value = CONFIG.maxTokens; | |
| $('set-temp').value = CONFIG.temperature; | |
| $('set-rounds').value = CONFIG.rounds; | |
| $('set-economy').checked = CONFIG.economy; | |
| $('set-theme').checked = document.body.classList.contains('light'); | |
| settingsModal.classList.add('open'); | |
| }); | |
| $('settings-cancel').addEventListener('click', () => settingsModal.classList.remove('open')); | |
| settingsModal.addEventListener('click', e => { if (e.target === settingsModal) settingsModal.classList.remove('open'); }); | |
| $('set-model').addEventListener('change', () => { | |
| const [repo, file] = $('set-model').value.split('|'); | |
| $('set-repo').value = repo; $('set-file').value = file; | |
| }); | |
| $('apply-settings').addEventListener('click', async () => { | |
| const prof = PROFILES[$('set-profile').value]; | |
| CONFIG.maxTokens = parseInt($('set-maxtokens').value) || prof.maxTokens; | |
| CONFIG.temperature = parseFloat($('set-temp').value) || prof.temperature; | |
| CONFIG.rounds = Math.min(6, Math.max(1, parseInt($('set-rounds').value) || prof.rounds)); | |
| CONFIG.economy = $('set-economy').checked; | |
| document.body.classList.toggle('light', $('set-theme').checked); | |
| const newCtx = parseInt($('set-ctx').value) || prof.nCtx; | |
| const newRepo = $('set-repo').value.trim(); | |
| const newFile = $('set-file').value.trim(); | |
| if (CONFIG.economy) { CONFIG.maxTokens = Math.min(CONFIG.maxTokens, 160); } | |
| const reload = newCtx !== CONFIG.nCtx || newRepo !== CONFIG.repo || newFile !== CONFIG.file; | |
| CONFIG.nCtx = newCtx; CONFIG.repo = newRepo; CONFIG.file = newFile; | |
| settingsModal.classList.remove('open'); | |
| if (reload || !wllama) { transcript = []; chatEl.innerHTML = ''; await loadModel(CONFIG.repo, CONFIG.file); } | |
| else setStatus('Ajustes aplicados.'); | |
| }); | |
| /* ================= Init ================= */ | |
| renderRoster(); | |
| renderPresets(); | |
| renderTemplates(); | |
| engineBadge(); | |
| updateStorageStat(); | |
| if (CONFIG.autoload) loadModel(CONFIG.repo, CONFIG.file); | |
| else setStatus('Modo manual: carga el modelo desde Ajustes (\u2699\uFE0F).'); | |
| </script> | |
| </body> | |
| </html> |