fivetech commited on
Commit
c480d3b
·
verified ·
1 Parent(s): d310efe

Create index.html

Browse files
Files changed (1) hide show
  1. index.html +1616 -19
index.html CHANGED
@@ -1,19 +1,1616 @@
1
- <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
19
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="es">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Multi-Agent Lab — WebGPU</title>
7
+ <meta name="description" content="Laboratorio de inteligencia colectiva: agentes de IA locales razonan, se contradicen, investigan y construyen una respuesta consensuada en tu navegador.">
8
+ <style>
9
+ :root{
10
+ --bg:#0b0f14; --bg2:#0f151d; --panel:#121a24; --panel2:#16202d; --border:#233043;
11
+ --text:#e6edf3; --muted:#8b9bb0; --accent:#2dd4bf; --accent2:#22d3ee; --violet:#a78bfa;
12
+ --green:#34d399; --yellow:#fbbf24; --red:#f87171; --orange:#fb923c;
13
+ --radius:14px;
14
+ }
15
+ body.light{
16
+ --bg:#f3f6fa; --bg2:#ffffff; --panel:#ffffff; --panel2:#eef2f7; --border:#d3dde8;
17
+ --text:#13202f; --muted:#5b6b7f;
18
+ }
19
+ *{box-sizing:border-box;margin:0;padding:0}
20
+ html,body{height:100%}
21
+ body{
22
+ background:radial-gradient(1200px 600px at 80% -10%, #12302b55, transparent),
23
+ radial-gradient(900px 500px at 10% 110%, #1c2a4a44, transparent), var(--bg);
24
+ color:var(--text); font-family:'Segoe UI',system-ui,-apple-system,sans-serif;
25
+ display:flex; flex-direction:column; min-height:100vh;
26
+ }
27
+ body.light{background:var(--bg)}
28
+ a{color:var(--accent2)}
29
+ button{font-family:inherit;cursor:pointer}
30
+ .hidden{display:none !important}
31
+
32
+ /* ---------- Header ---------- */
33
+ header{
34
+ display:flex;align-items:center;gap:14px;flex-wrap:wrap;
35
+ padding:10px 18px;border-bottom:1px solid var(--border);
36
+ background:color-mix(in srgb, var(--bg2) 88%, transparent);backdrop-filter:blur(8px);
37
+ position:sticky;top:0;z-index:50;
38
+ }
39
+ .logo{display:flex;align-items:center;gap:10px}
40
+ .logo .mark{font-size:26px;filter:drop-shadow(0 0 8px var(--accent))}
41
+ .logo h1{font-size:17px;letter-spacing:2px;font-weight:800;
42
+ background:linear-gradient(90deg,var(--accent),var(--accent2),var(--violet));
43
+ -webkit-background-clip:text;background-clip:text;color:transparent;white-space:nowrap}
44
+ .logo .tagline{font-size:9.5px;letter-spacing:3px;color:var(--muted);white-space:nowrap}
45
+ nav.tabs{display:flex;gap:4px;flex-wrap:wrap;margin-left:auto}
46
+ nav.tabs button{
47
+ background:transparent;border:1px solid transparent;color:var(--muted);
48
+ padding:7px 13px;border-radius:999px;font-size:13px;font-weight:600;transition:.15s;
49
+ }
50
+ nav.tabs button:hover{color:var(--text);border-color:var(--border)}
51
+ nav.tabs button.active{color:#06231f;background:linear-gradient(90deg,var(--accent),var(--accent2));
52
+ box-shadow:0 0 14px #2dd4bf55}
53
+ body.light nav.tabs button.active{color:#fff}
54
+ .model-pill{display:flex;align-items:center;gap:7px;font-size:11.5px;color:var(--muted);
55
+ border:1px solid var(--border);border-radius:999px;padding:5px 11px;background:var(--panel)}
56
+ .model-pill .dot{width:8px;height:8px;border-radius:50%;background:var(--yellow)}
57
+ .model-pill.ready .dot{background:var(--green);box-shadow:0 0 8px var(--green)}
58
+ .model-pill.error .dot{background:var(--red)}
59
+
60
+ /* ---------- Layout ---------- */
61
+ main{flex:1;width:100%;max-width:1280px;margin:0 auto;padding:16px 18px 40px}
62
+ section.tabpage{display:none;animation:fadein .2s}
63
+ section.tabpage.active{display:block}
64
+ @keyframes fadein{from{opacity:0;transform:translateY(4px)}to{opacity:1}}
65
+ .panel{background:var(--panel);border:1px solid var(--border);border-radius:var(--radius);padding:16px}
66
+ .panel h2{font-size:14px;letter-spacing:1.5px;text-transform:uppercase;color:var(--accent);margin-bottom:10px}
67
+ .panel h3{font-size:13px;color:var(--text);margin:12px 0 6px}
68
+ .muted{color:var(--muted);font-size:12.5px;line-height:1.5}
69
+ .btn{
70
+ background:linear-gradient(90deg,var(--accent),var(--accent2));color:#06231f;border:none;
71
+ border-radius:999px;padding:9px 18px;font-weight:700;font-size:13.5px;transition:.15s;
72
+ }
73
+ body.light .btn{color:#fff}
74
+ .btn:hover:not(:disabled){filter:brightness(1.1);box-shadow:0 0 14px #2dd4bf66}
75
+ .btn:disabled{opacity:.45;cursor:not-allowed}
76
+ .btn.ghost{background:transparent;border:1px solid var(--border);color:var(--text)}
77
+ .btn.ghost:hover:not(:disabled){border-color:var(--accent);color:var(--accent);box-shadow:none}
78
+ .btn.danger{background:transparent;border:1px solid var(--red);color:var(--red)}
79
+ .btn.small{padding:5px 11px;font-size:12px}
80
+ input,select,textarea{
81
+ background:var(--bg2);border:1px solid var(--border);color:var(--text);
82
+ border-radius:9px;padding:8px 11px;font-size:13.5px;font-family:inherit;width:100%;
83
+ }
84
+ input:focus,select:focus,textarea:focus{outline:none;border-color:var(--accent)}
85
+ textarea{resize:vertical;min-height:70px}
86
+ label.f{display:block;font-size:12px;color:var(--muted);margin:9px 0 3px}
87
+ .badge{display:inline-block;font-size:10.5px;font-weight:700;padding:2px 8px;border-radius:999px;
88
+ border:1px solid var(--border);color:var(--muted);letter-spacing:.5px;vertical-align:middle}
89
+ .badge.role{color:var(--violet);border-color:var(--violet)}
90
+ .badge.webgpu{color:var(--green);border-color:var(--green)}
91
+ .badge.cpu{color:var(--yellow);border-color:var(--yellow)}
92
+ .badge.warn{color:var(--orange);border-color:var(--orange)}
93
+ .disclaimer{font-size:11.5px;color:var(--muted);border:1px dashed var(--border);
94
+ border-radius:9px;padding:8px 11px;margin-top:10px;line-height:1.5}
95
+ </style>
96
+ <style>
97
+ /* ---------- Agentes ---------- */
98
+ .roster{display:grid;grid-template-columns:repeat(auto-fill,minmax(215px,1fr));gap:12px;margin-top:12px}
99
+ .acard{background:var(--panel2);border:1px solid var(--border);border-radius:var(--radius);
100
+ padding:13px;display:flex;flex-direction:column;gap:7px;position:relative;transition:.15s}
101
+ .acard:hover{border-color:var(--accent)}
102
+ .acard .ahead{display:flex;align-items:center;gap:10px}
103
+ .avatar{width:38px;height:38px;border-radius:50%;display:flex;align-items:center;justify-content:center;
104
+ font-size:19px;flex-shrink:0;border:1px solid #ffffff22}
105
+ .acard .aname{font-weight:700;font-size:14.5px}
106
+ .acard .aspec{font-size:11.5px;color:var(--accent2)}
107
+ .acard .apers{font-size:12px;color:var(--muted);line-height:1.45;
108
+ display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}
109
+ .acard .act{display:flex;gap:6px;margin-top:auto}
110
+ .preset-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:9px;margin-top:10px}
111
+ .preset{background:var(--panel2);border:1px dashed var(--border);border-radius:11px;padding:10px;
112
+ cursor:pointer;text-align:center;transition:.15s}
113
+ .preset:hover{border-color:var(--accent);transform:translateY(-2px)}
114
+ .preset .pe{font-size:22px}
115
+ .preset .pn{font-size:12.5px;font-weight:700;margin-top:3px}
116
+ .preset .ps{font-size:10.5px;color:var(--muted)}
117
+
118
+ /* ---------- Debate ---------- */
119
+ .debate-layout{display:grid;grid-template-columns:1fr 285px;gap:14px;align-items:start}
120
+ @media(max-width:900px){.debate-layout{grid-template-columns:1fr}}
121
+ .modes{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:8px;margin:10px 0}
122
+ .mode-card{background:var(--panel2);border:1px solid var(--border);border-radius:11px;
123
+ padding:10px;cursor:pointer;text-align:center;transition:.15s}
124
+ .mode-card:hover{border-color:var(--accent2)}
125
+ .mode-card.sel{border-color:var(--accent);box-shadow:0 0 12px #2dd4bf44;background:#14b8a611}
126
+ body.light .mode-card.sel{background:#14b8a622}
127
+ .mode-card .me{font-size:21px}
128
+ .mode-card .mn{font-size:12px;font-weight:700;margin:3px 0 2px}
129
+ .mode-card .md{font-size:10px;color:var(--muted);line-height:1.35}
130
+ .topic-row{display:flex;gap:8px;margin-top:8px}
131
+ .topic-row input{flex:1}
132
+ .chat{background:var(--bg2);border:1px solid var(--border);border-radius:var(--radius);
133
+ padding:14px;margin-top:12px;min-height:220px;max-height:560px;overflow-y:auto}
134
+ .msg{display:flex;gap:10px;margin-bottom:13px;align-items:flex-start}
135
+ .msg .content{flex:1;min-width:0}
136
+ .msg .who{font-size:12px;font-weight:700;margin-bottom:3px;display:flex;gap:7px;align-items:center;flex-wrap:wrap}
137
+ .msg .body{font-size:13.5px;line-height:1.55;background:var(--panel);border:1px solid var(--border);
138
+ border-radius:4px 13px 13px 13px;padding:9px 12px;overflow-wrap:break-word}
139
+ .msg.user .body{background:#14b8a617;border-color:var(--accent)}
140
+ .msg.streaming .body{border-color:var(--accent2);box-shadow:0 0 10px #22d3ee33}
141
+ .msg.err .body{border-color:var(--red);color:var(--red)}
142
+ .msg.devil .body{border-color:var(--red);background:#f8717110}
143
+ .msg.system-note .body{background:transparent;border:1px dashed var(--border);color:var(--muted);font-size:12px}
144
+ .msg .meta{font-size:10.5px;color:var(--muted);margin-top:3px}
145
+ .msg .body p{margin:0 0 6px}.msg .body p:last-child{margin:0}
146
+ details.think{margin:4px 0;font-size:11.5px;color:var(--muted)}
147
+ details.think summary{cursor:pointer;color:var(--accent2)}
148
+ details.think div{white-space:pre-wrap;border-left:2px solid var(--border);padding-left:8px;margin-top:4px}
149
+ .chip-change{font-size:10px;font-weight:700;color:var(--orange);border:1px solid var(--orange);
150
+ border-radius:999px;padding:1px 7px}
151
+ .controls{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-top:10px}
152
+ .interject{display:flex;gap:8px;margin-top:10px}
153
+ .stats-side{display:flex;flex-direction:column;gap:12px;position:sticky;top:76px}
154
+ .stat-row{display:flex;justify-content:space-between;font-size:12.5px;padding:4px 0;border-bottom:1px solid var(--border)}
155
+ .stat-row:last-child{border-bottom:none}
156
+ .stat-row b{color:var(--accent2)}
157
+ .pbar{height:6px;background:var(--bg2);border-radius:99px;overflow:hidden;margin-top:6px}
158
+ .pbar>div{height:100%;width:0;background:linear-gradient(90deg,var(--accent),var(--accent2));transition:width .3s}
159
+ .agent-stat{display:flex;align-items:center;gap:8px;font-size:12px;margin:5px 0}
160
+ .agent-stat .avatar{width:24px;height:24px;font-size:12px}
161
+ .agent-stat .nm{width:74px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
162
+ .agent-stat .bar{flex:1;height:5px;background:var(--bg2);border-radius:99px;overflow:hidden}
163
+ .agent-stat .bar>div{height:100%}
164
+ .agent-stat .tk{width:62px;text-align:right;color:var(--muted);font-size:11px}
165
+
166
+ /* ---------- Análisis ---------- */
167
+ .consensus-hero{display:flex;align-items:center;gap:14px;padding:14px;border-radius:var(--radius);
168
+ border:1px solid var(--border);margin-bottom:14px;background:var(--panel2)}
169
+ .consensus-hero .ci{font-size:32px}
170
+ .consensus-hero .cs{font-size:16px;font-weight:800}
171
+ .consensus-hero.ok .cs{color:var(--green)}.consensus-hero.partial .cs{color:var(--yellow)}
172
+ .consensus-hero.disagree .cs{color:var(--red)}
173
+ .score-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:12px;margin-top:10px}
174
+ .scard{background:var(--panel2);border:1px solid var(--border);border-radius:var(--radius);padding:13px}
175
+ .scard .stop{display:flex;align-items:center;gap:10px}
176
+ .scard .big{font-size:26px;font-weight:800;margin-left:auto;color:var(--accent)}
177
+ .scard .crit{display:grid;grid-template-columns:1fr;gap:4px;margin-top:9px}
178
+ .scard .crow{display:flex;align-items:center;gap:7px;font-size:11px;color:var(--muted)}
179
+ .scard .crow .lb{width:118px;flex-shrink:0}
180
+ .scard .crow .bar{flex:1;height:5px;background:var(--bg2);border-radius:99px;overflow:hidden}
181
+ .scard .crow .bar>div{height:100%;background:var(--accent2)}
182
+ .scard .crow .vl{width:20px;text-align:right;color:var(--text)}
183
+ .scard .comment{font-size:12px;color:var(--muted);margin-top:8px;line-height:1.5;font-style:italic}
184
+ .vote-list{font-size:12.5px;margin-top:8px;display:flex;flex-direction:column;gap:5px}
185
+ .vote-list .vrow{display:flex;gap:8px;align-items:baseline}
186
+ .vote-list .vv{font-weight:800;width:64px;flex-shrink:0}
187
+ .vote-list .vv.si{color:var(--green)}.vote-list .vv.parcial{color:var(--yellow)}.vote-list .vv.no{color:var(--red)}
188
+ .argmap{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-top:10px;position:relative}
189
+ @media(max-width:800px){.argmap{grid-template-columns:repeat(2,1fr)}}
190
+ .argcol h4{font-size:11px;letter-spacing:1px;text-transform:uppercase;margin-bottom:8px;text-align:center}
191
+ .argcol.tesis h4{color:var(--accent)}.argcol.evid h4{color:var(--accent2)}
192
+ .argcol.obj h4{color:var(--orange)}.argcol.concl h4{color:var(--violet)}
193
+ .argnode{background:var(--panel2);border:1px solid var(--border);border-left:3px solid var(--accent);
194
+ border-radius:9px;padding:8px 10px;font-size:12px;line-height:1.45;margin-bottom:8px}
195
+ .argcol.evid .argnode{border-left-color:var(--accent2)}
196
+ .argcol.obj .argnode{border-left-color:var(--orange)}
197
+ .argcol.concl .argnode{border-left-color:var(--violet)}
198
+ .relchips{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}
199
+ .relchip{font-size:11.5px;border-radius:999px;padding:3px 10px;border:1px solid var(--border)}
200
+ .relchip.sup{color:var(--green);border-color:var(--green)}
201
+ .relchip.con{color:var(--red);border-color:var(--red)}
202
+ .timeline{margin-top:10px}
203
+ .tl-round{margin-bottom:14px}
204
+ .tl-round h4{font-size:12px;color:var(--accent2);margin-bottom:6px;letter-spacing:1px}
205
+ .tl-item{display:flex;gap:9px;font-size:12.5px;margin:5px 0;align-items:baseline}
206
+ .tl-item .who{width:110px;flex-shrink:0;font-weight:700}
207
+ .tl-item .what{color:var(--muted);line-height:1.45}
208
+
209
+ /* ---------- Conocimiento / Historial ---------- */
210
+ .mem-item,.lib-item{background:var(--panel2);border:1px solid var(--border);border-radius:11px;
211
+ padding:11px 13px;margin-bottom:9px}
212
+ .mem-item .mt,.lib-item .mt{font-weight:700;font-size:13.5px}
213
+ .mem-item .mm,.lib-item .mm{font-size:11px;color:var(--muted);margin:3px 0}
214
+ .mem-item .mc{font-size:12.5px;color:var(--text);line-height:1.5}
215
+ .lib-item .actions{display:flex;gap:6px;flex-wrap:wrap;margin-top:8px}
216
+ .rank-table{width:100%;border-collapse:collapse;font-size:13px;margin-top:8px}
217
+ .rank-table th,.rank-table td{padding:7px 9px;text-align:left;border-bottom:1px solid var(--border)}
218
+ .rank-table th{color:var(--accent);font-size:11px;text-transform:uppercase;letter-spacing:1px}
219
+ .rank-table td.num{text-align:right}
220
+
221
+ /* ---------- Modal ---------- */
222
+ .modal{position:fixed;inset:0;background:#0009;display:none;align-items:center;justify-content:center;
223
+ z-index:100;padding:16px}
224
+ .modal.open{display:flex}
225
+ .modal .box{background:var(--panel);border:1px solid var(--border);border-radius:var(--radius);
226
+ padding:20px;width:100%;max-width:520px;max-height:88vh;overflow-y:auto}
227
+ .modal h3{font-size:15px;margin-bottom:8px;color:var(--accent)}
228
+ .modal .row2{display:grid;grid-template-columns:1fr 1fr;gap:10px}
229
+ .modal .brow{display:flex;gap:8px;justify-content:flex-end;margin-top:14px}
230
+
231
+ /* ---------- Toast / fase ---------- */
232
+ .phase-note{display:flex;align-items:center;gap:9px;background:var(--panel2);
233
+ border:1px solid var(--border);border-left:3px solid var(--accent2);border-radius:9px;
234
+ padding:9px 12px;font-size:12.5px;margin:10px 0}
235
+ .spin{display:inline-block;animation:sp 1s linear infinite}
236
+ @keyframes sp{to{transform:rotate(360deg)}}
237
+
238
+ @media print{
239
+ body{background:#fff;color:#000}
240
+ header,nav.tabs,.controls,.interject,.stats-side,.btn{display:none !important}
241
+ .panel,.scard,.mem-item,.lib-item{border:1px solid #ccc;background:#fff;color:#000}
242
+ .msg .body{background:#fff;border:1px solid #ccc;color:#000}
243
+ section.tabpage{display:block !important}
244
+ }
245
+ </style>
246
+ </head>
247
+ <body>
248
+ <header>
249
+ <div class="logo">
250
+ <div class="mark">🧠</div>
251
+ <div>
252
+ <h1>MULTI-AGENT LAB</h1>
253
+ <div class="tagline">INTELLIGENCE · DEBATE · REASONING</div>
254
+ </div>
255
+ </div>
256
+ <div class="model-pill" id="model-pill"><span class="dot"></span><span id="model-pill-txt">sin modelo</span></div>
257
+ <nav class="tabs">
258
+ <button data-tab="agentes">🧬 Agentes</button>
259
+ <button data-tab="debate" class="active">💬 Debate</button>
260
+ <button data-tab="analisis">📊 Análisis</button>
261
+ <button data-tab="conocimiento">📚 Conocimiento</button>
262
+ <button data-tab="historial">🗂️ Historial</button>
263
+ <button id="settings-btn" title="Ajustes">⚙️</button>
264
+ </nav>
265
+ </header>
266
+
267
+ <main>
268
+ <!-- ============ AGENTES ============ -->
269
+ <section class="tabpage" id="page-agentes">
270
+ <div class="panel">
271
+ <h2>Configurar — Equipo de agentes</h2>
272
+ <div class="muted">Crea tu equipo: cada agente tiene especialidad, personalidad y ajustes propios de temperatura y longitud.
273
+ 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>
274
+ <div class="roster" id="roster"></div>
275
+ <h3>Perfiles prediseñados — toca para añadir</h3>
276
+ <div class="preset-grid" id="presets"></div>
277
+ <div class="controls">
278
+ <button class="btn" id="add-agent">+ Nuevo agente</button>
279
+ <button class="btn ghost" id="reset-agents">Restablecer equipo base</button>
280
+ </div>
281
+ </div>
282
+ <div class="panel" style="margin-top:14px">
283
+ <h2>Biblioteca de plantillas</h2>
284
+ <div class="muted">Paquetes listos para usar: aplican modo, equipo y tema de una vez.</div>
285
+ <div class="preset-grid" id="templates"></div>
286
+ </div>
287
+ </section>
288
+
289
+ <!-- ============ DEBATE ============ -->
290
+ <section class="tabpage active" id="page-debate">
291
+ <div class="panel">
292
+ <h2>Interactuar — Sesión de debate</h2>
293
+ <div class="modes" id="modes"></div>
294
+ <label class="f">Tema, problema o experimento mental</label>
295
+ <div class="topic-row">
296
+ <input id="topic" placeholder="¿Es posible desarrollar una IA verdaderamente autónoma?" autocomplete="off">
297
+ <select id="topic-sugg" style="max-width:215px"></select>
298
+ </div>
299
+ <div class="controls">
300
+ <button class="btn" id="start-btn" disabled>Cargando modelo&hellip;</button>
301
+ <button class="btn danger hidden" id="stop-btn">⏸ Pausar</button>
302
+ <button class="btn ghost" id="devil-btn" disabled>👿 Devil's Advocate</button>
303
+ <span class="muted" id="status">Iniciando…</span>
304
+ </div>
305
+ <div class="pbar"><div id="progress-fill"></div></div>
306
+ <div class="chat" id="chat"></div>
307
+ <div class="interject">
308
+ <input id="interject-txt" placeholder="Introdúcete en el debate en cualquier momento…" autocomplete="off">
309
+ <button class="btn ghost" id="interject-btn">Intervenir</button>
310
+ </div>
311
+ </div>
312
+ <div class="stats-side" style="margin-top:14px">
313
+ <div class="panel">
314
+ <h2>Estadísticas en vivo</h2>
315
+ <div class="stat-row"><span>Ronda / fase</span><b id="st-round">—</b></div>
316
+ <div class="stat-row"><span>Turnos</span><b id="st-turns">0</b></div>
317
+ <div class="stat-row"><span>Tokens generados</span><b id="st-tokens">0</b></div>
318
+ <div class="stat-row"><span>Velocidad (últ. / media)</span><b id="st-speed">—</b></div>
319
+ <div class="stat-row"><span>Tiempo de debate</span><b id="st-time">0:00</b></div>
320
+ <div class="stat-row"><span>Motor</span><b id="st-engine">—</b></div>
321
+ <div class="stat-row"><span>Almacenamiento</span><b id="st-mem">—</b></div>
322
+ <h3>Participación</h3>
323
+ <div id="st-agents"></div>
324
+ </div>
325
+ </div>
326
+ </section>
327
+
328
+ <!-- ============ ANÁLISIS ============ -->
329
+ <section class="tabpage" id="page-analisis">
330
+ <div class="panel">
331
+ <h2>Evaluar — Consenso y evaluación</h2>
332
+ <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>
333
+ <div class="controls"><button class="btn" id="analyze-btn" disabled>Analizar ahora</button>
334
+ <button class="btn ghost" id="devil-btn2" disabled>👿 Devil's Advocate</button></div>
335
+ <div id="analysis-out"></div>
336
+ <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.
337
+ Son resultados orientativos para explorar el razonamiento, no mediciones objetivas ni evaluaciones independientes.</div>
338
+ </div>
339
+ </section>
340
+
341
+ <!-- ============ CONOCIMIENTO ============ -->
342
+ <section class="tabpage" id="page-conocimiento">
343
+ <div class="panel">
344
+ <h2>Conectar — Memoria de debates</h2>
345
+ <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>
346
+ <div class="controls">
347
+ <label style="font-size:13px;display:flex;gap:7px;align-items:center;cursor:pointer">
348
+ <input type="checkbox" id="mem-inject" style="width:auto"> Usar memoria en futuros debates</label>
349
+ <button class="btn ghost small" id="mem-clear">Vaciar memoria</button>
350
+ </div>
351
+ <div id="mem-list" style="margin-top:10px"></div>
352
+ </div>
353
+ <div class="panel" style="margin-top:14px">
354
+ <h2>Ranking histórico de agentes</h2>
355
+ <div class="muted">Media de las puntuaciones del evaluador en este navegador. Orientativo: mismo modelo, no objetivo.</div>
356
+ <div id="ranking-out"></div>
357
+ </div>
358
+ </section>
359
+
360
+ <!-- ============ HISTORIAL ============ -->
361
+ <section class="tabpage" id="page-historial">
362
+ <div class="panel">
363
+ <h2>Recuperar — Biblioteca de debates</h2>
364
+ <div class="topic-row">
365
+ <input id="lib-search" placeholder="Buscar por tema, modo o agente…">
366
+ <button class="btn ghost" id="lib-clear">Borrar biblioteca</button>
367
+ </div>
368
+ <div id="lib-list" style="margin-top:12px"></div>
369
+ </div>
370
+ </section>
371
+ </main>
372
+
373
+ <!-- ============ MODAL AGENTE ============ -->
374
+ <div class="modal" id="agent-modal">
375
+ <div class="box">
376
+ <h3 id="agent-modal-title">Editar agente</h3>
377
+ <div class="row2">
378
+ <div><label class="f">Nombre</label><input id="agent-name"></div>
379
+ <div><label class="f">Emoji</label><input id="agent-emoji" maxlength="4"></div>
380
+ </div>
381
+ <div class="row2">
382
+ <div><label class="f">Color</label><input id="agent-color" type="color" style="height:36px;padding:3px"></div>
383
+ <div><label class="f">Especialidad</label><input id="agent-spec" placeholder="Ciencia, economía…"></div>
384
+ </div>
385
+ <label class="f">Personalidad e instrucciones</label>
386
+ <textarea id="agent-system" rows="4"></textarea>
387
+ <div class="row2">
388
+ <div><label class="f">Temperatura (0–1.5)</label><input id="agent-temp" type="number" step="0.05" min="0" max="1.5"></div>
389
+ <div><label class="f">Máx. tokens por turno</label><input id="agent-maxtokens" type="number" step="16" min="64" max="1024"></div>
390
+ </div>
391
+ <div class="brow">
392
+ <button class="btn danger" id="agent-delete">Eliminar</button>
393
+ <button class="btn ghost" id="agent-cancel">Cancelar</button>
394
+ <button class="btn" id="agent-save">Guardar</button>
395
+ </div>
396
+ </div>
397
+ </div>
398
+
399
+ <!-- ============ MODAL AJUSTES ============ -->
400
+ <div class="modal" id="settings-modal">
401
+ <div class="box">
402
+ <h3>Ajustes del laboratorio</h3>
403
+ <label class="f">Perfil de rendimiento</label>
404
+ <select id="set-profile">
405
+ <option value="low">Gama baja — contexto 2048, respuestas cortas</option>
406
+ <option value="mid" selected>Gama media — contexto 4096</option>
407
+ <option value="high">Gama alta — contexto 8192, respuestas largas</option>
408
+ </select>
409
+ <label class="f">Modelo (GGUF en Hugging Face)</label>
410
+ <select id="set-model">
411
+ <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>
412
+ <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>
413
+ <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>
414
+ </select>
415
+ <div class="row2">
416
+ <div><label class="f">Repositorio</label><input id="set-repo"></div>
417
+ <div><label class="f">Archivo</label><input id="set-file"></div>
418
+ </div>
419
+ <div class="row2">
420
+ <div><label class="f">Contexto (tokens)</label><input id="set-ctx" type="number"></div>
421
+ <div><label class="f">Rondas por debate</label><input id="set-rounds" type="number" min="1" max="6"></div>
422
+ </div>
423
+ <div class="row2">
424
+ <div><label class="f">Temperatura global</label><input id="set-temp" type="number" step="0.05"></div>
425
+ <div><label class="f">Máx. tokens por turno</label><input id="set-maxtokens" type="number"></div>
426
+ </div>
427
+ <label style="font-size:13px;display:flex;gap:7px;align-items:center;margin-top:10px;cursor:pointer">
428
+ <input type="checkbox" id="set-economy" style="width:auto"> Modo ahorro: limita contexto y longitud para equipos modestos</label>
429
+ <label style="font-size:13px;display:flex;gap:7px;align-items:center;margin-top:6px;cursor:pointer">
430
+ <input type="checkbox" id="set-theme" style="width:auto"> Tema claro</label>
431
+ <div class="brow">
432
+ <button class="btn ghost" id="settings-cancel">Cerrar</button>
433
+ <button class="btn" id="apply-settings">Aplicar</button>
434
+ </div>
435
+ </div>
436
+ </div>
437
+ <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
438
+ <script type="module">
439
+ import { Wllama } from 'https://cdn.jsdelivr.net/npm/@wllama/wllama@3.5.1/esm/index.js';
440
+
441
+ const params = new URLSearchParams(location.search);
442
+ const $ = id => document.getElementById(id);
443
+
444
+ /* ================= Config ================= */
445
+ const CONFIG = {
446
+ modelUrl: params.get('modelUrl') || '',
447
+ repo: params.get('repo') || 'Qwen/Qwen2.5-0.5B-Instruct-GGUF',
448
+ file: params.get('file') || 'qwen2.5-0.5b-instruct-q4_k_m.gguf',
449
+ nCtx: parseInt(params.get('ctx')) || 4096,
450
+ maxTokens: parseInt(params.get('maxTokens')) || 256,
451
+ temperature: parseFloat(params.get('temp')) || 0.7,
452
+ rounds: Math.min(6, Math.max(1, parseInt(params.get('rounds')) || 2)),
453
+ autoload: params.get('autoload') !== 'false',
454
+ economy: false,
455
+ };
456
+ const PROFILES = {
457
+ low: { nCtx: 2048, maxTokens: 160, rounds: 2, temperature: 0.6 },
458
+ mid: { nCtx: 4096, maxTokens: 256, rounds: 2, temperature: 0.7 },
459
+ high: { nCtx: 8192, maxTokens: 420, rounds: 3, temperature: 0.8 },
460
+ };
461
+ if (params.get('theme') === 'light') document.body.classList.add('light');
462
+
463
+ /* ================= Datos base ================= */
464
+ const DEFAULT_AGENTS = [
465
+ { name: 'Ada', emoji: '\u{1F9EA}', color: '#2dd4bf', specialty: 'Ciencia',
466
+ system: 'Eres Ada, cient\u00edfica del laboratorio. Razonas con datos, pides evidencia y formulas hip\u00f3tesis comprobables. Reconoces la incertidumbre cuando existe.',
467
+ temp: 0.7, maxTokens: 256 },
468
+ { name: 'Bruno', emoji: '\u{1F9D0}', color: '#fb923c', specialty: 'Cr\u00edtica l\u00f3gica',
469
+ 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.',
470
+ temp: 0.7, maxTokens: 256 },
471
+ { name: 'Carla', emoji: '\u{1F3AF}', color: '#a78bfa', specialty: 'S\u00edntesis',
472
+ system: 'Eres Carla, la moderadora del laboratorio. Integras los desacuerdos, resumes posiciones y propones s\u00edntesis o el siguiente paso.',
473
+ temp: 0.6, maxTokens: 256 },
474
+ ];
475
+ const PRESETS = [
476
+ { name: 'Cient\u00edfico', emoji: '\u{1F52C}', color: '#22d3ee', specialty: 'Ciencia',
477
+ system: 'Eres un cient\u00edfico riguroso. Basa cada afirmaci\u00f3n en evidencia, distingue correlaci\u00f3n de causalidad y propone c\u00f3mo comprobar las ideas.' },
478
+ { name: 'Economista', emoji: '\u{1F4C8}', color: '#34d399', specialty: 'Econom\u00eda',
479
+ system: 'Eres un economista. Analizas incentivos, costes, beneficios y consecuencias de segundo orden. Cuantifica cuando puedas.' },
480
+ { name: 'Fil\u00f3sofo', emoji: '\u{1F989}', color: '#a78bfa', specialty: '\u00c9tica y filosof\u00eda',
481
+ system: 'Eres un fil\u00f3sofo. Examina principios, valores y dilemas \u00e9ticos. Pregunta por el porqu\u00e9 \u00faltimo de cada postura.' },
482
+ { name: 'Ingeniero', emoji: '\u{1F527}', color: '#fbbf24', specialty: 'Ingenier\u00eda',
483
+ system: 'Eres un ingeniero pragm\u00e1tico. Eval\u00faas viabilidad t\u00e9cnica, recursos, plazos y puntos de fallo. Propone soluciones construibles.' },
484
+ { name: 'Abogado', emoji: '\u2696\uFE0F', color: '#f87171', specialty: 'Derecho',
485
+ system: 'Eres un abogado. Argumentas con precedentes y normas, detectas lagunas legales y defiendes tu posici\u00f3n con precisi\u00f3n.' },
486
+ { name: 'Creativo', emoji: '\u{1F3A8}', color: '#f472b6', specialty: 'Ideaci\u00f3n',
487
+ system: 'Eres un pensador creativo. Propones ideas originales, analog\u00edas y escenarios que los dem\u00e1s no han considerado.' },
488
+ { name: 'Historiador', emoji: '\u{1F4DC}', color: '#d4a373', specialty: 'Historia',
489
+ system: 'Eres un historiador. Comparas con precedentes hist\u00f3ricos y adviertes qu\u00e9 sali\u00f3 bien o mal en casos anteriores.' },
490
+ { name: 'Psic\u00f3logo', emoji: '\u{1F9E0}', color: '#7dd3fc', specialty: 'Conducta',
491
+ system: 'Eres un psic\u00f3logo. Analizas motivaciones, sesgos cognitivos e impacto humano de cada propuesta.' },
492
+ ];
493
+ const MODES = {
494
+ adversarial: { emoji: '\u2694\uFE0F', name: 'Adversarial', desc: 'Uno propone, otro ataca, otro defiende' },
495
+ consejo: { emoji: '\u{1F3DB}\uFE0F', name: 'Consejo', desc: 'Perfiles que buscan una decisi\u00f3n conjunta' },
496
+ juicio: { emoji: '\u2696\uFE0F', name: 'Juicio', desc: 'Fiscal, defensa y veredicto del juez' },
497
+ investigacion: { emoji: '\u{1F52C}', name: 'Investigaci\u00f3n', desc: 'Hip\u00f3tesis, contradicciones y experimentos' },
498
+ resolucion: { emoji: '\u{1F3AF}', name: 'Resoluci\u00f3n', desc: 'Soluciones que se comparan y combinan' },
499
+ };
500
+ const TEMPLATES = [
501
+ { name: '\u00c9tica de la IA', emoji: '\u{1F916}', mode: 'consejo',
502
+ topic: '\u00bfDeber\u00eda regularse ya la IA generativa o frenar\u00eda la innovaci\u00f3n?',
503
+ agents: ['Cient\u00edfico', 'Fil\u00f3sofo', 'Ingeniero', 'Abogado'] },
504
+ { name: 'Juicio: redes sociales', emoji: '\u2696\uFE0F', mode: 'juicio',
505
+ topic: 'Juicio: \u00bfson las redes sociales culpables del deterioro del debate p\u00fablico?',
506
+ agents: ['Abogado', 'Psic\u00f3logo', 'Cient\u00edfico'] },
507
+ { name: 'Energ\u00eda del futuro', emoji: '\u26A1', mode: 'investigacion',
508
+ topic: '\u00bfCu\u00e1l es la fuente de energ\u00eda m\u00e1s prometedora para 2050?',
509
+ agents: ['Cient\u00edfico', 'Ingeniero', 'Economista'] },
510
+ { name: 'Mercado vs regulaci\u00f3n', emoji: '\u2694\uFE0F', mode: 'adversarial',
511
+ topic: '\u00bfFunciona mejor el libre mercado o la regulaci\u00f3n estatal en sanidad?',
512
+ agents: ['Economista', 'Fil\u00f3sofo', 'Historiador'] },
513
+ { name: 'Experimento: un a\u00f1o sin Internet', emoji: '\u{1F310}', mode: 'investigacion',
514
+ topic: 'Experimento mental: \u00bfqu\u00e9 ocurrir\u00eda si ma\u00f1ana desapareciera Internet durante un a\u00f1o?',
515
+ agents: ['Economista', 'Psic\u00f3logo', 'Ingeniero', 'Historiador'] },
516
+ { name: 'Problema: vivienda', emoji: '\u{1F3E0}', mode: 'resolucion',
517
+ topic: '\u00bfC\u00f3mo resolver el problema del precio de la vivienda en las grandes ciudades?',
518
+ agents: ['Economista', 'Ingeniero', 'Abogado', 'Creativo'] },
519
+ ];
520
+ const TOPIC_POOL = [
521
+ '\u00bfEs posible desarrollar una inteligencia artificial verdaderamente aut\u00f3noma?',
522
+ '\u00bfConviene ejecutar LLMs en el navegador con WebGPU?',
523
+ 'Experimento mental: \u00bfqu\u00e9 ocurrir\u00eda si ma\u00f1ana desapareciera Internet durante un a\u00f1o?',
524
+ '\u00bfEs el trabajo remoto m\u00e1s productivo que la oficina?',
525
+ '\u00bfDeber\u00edan los coches aut\u00f3nomos decidir en un accidente?',
526
+ '\u00bfHa mejorado la IA la programaci\u00f3n o solo la ha acelerado?',
527
+ '\u00bfDebe durar un smartphone 7 a\u00f1os?',
528
+ '\u00bfEs la privacidad m\u00e1s importante que la comodidad?',
529
+ '\u00bfSobrevivir\u00e1 el open source a la IA?',
530
+ '\u00bfDeber\u00eda existir un derecho al olvido digital?',
531
+ '\u00bfTienen sentido los coches el\u00e9ctricos sin red de carga?',
532
+ '\u00bfDeben los ni\u00f1os aprender a programar antes de los 10 a\u00f1os?',
533
+ '\u00bfEs mejor vivir en la ciudad o en un pueblo?',
534
+ '\u00bfFue el 5G revoluci\u00f3n o marketing?',
535
+ 'Experimento mental: \u00bfy si toda la informaci\u00f3n del mundo fuera de acceso libre?',
536
+ ];
537
+
538
+ /* ================= Estado ================= */
539
+ const K = { agents: 'malab_agents', library: 'malab_library', memory: 'malab_memory',
540
+ ranking: 'malab_ranking', meminject: 'malab_meminject', settings: 'malab_settings' };
541
+ function lsGet(k, d) { try { const v = JSON.parse(localStorage.getItem(k)); return v ?? d; } catch (e) { return d; } }
542
+ function lsSet(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch (e) {} }
543
+
544
+ let agents = (() => {
545
+ const a = lsGet(K.agents, null);
546
+ return (Array.isArray(a) && a.length >= 2 && a.every(x => x && x.name && x.system)) ? a : DEFAULT_AGENTS.slice();
547
+ })();
548
+ let mode = 'adversarial';
549
+ let wllama = null, running = false, stopRequested = false, modelLoadMs = 0;
550
+ let topic = '';
551
+ let transcript = []; // {name, role, text, round, tokens, ms, isUser, kind}
552
+ let resume = { round: 1, stepIdx: 0, steps: null };
553
+ let stats = { tokens: {}, turns: {}, speeds: [], startTs: 0 };
554
+ let analysis = null; // {consensus, votes, conclusion, evaluation, relations, extra, argmap, devil}
555
+ let debateFinished = false;
556
+
557
+ function esc(s) { const d = document.createElement('div'); d.textContent = s; return d.innerHTML; }
558
+ function shade(hex, amt) {
559
+ const n = parseInt(String(hex).replace('#', '').slice(0, 6), 16);
560
+ if (isNaN(n)) return hex;
561
+ const f = v => Math.max(0, Math.min(255, v + amt));
562
+ return '#' + ((f(n >> 16) << 16) | (f((n >> 8) & 255) << 8) | f(n & 255)).toString(16).padStart(6, '0');
563
+ }
564
+ function avatarBg(c) { return `linear-gradient(135deg, ${shade(c, 34)} 0%, ${c} 55%, ${shade(c, -38)} 100%)`; }
565
+ function setStatus(t) { $('status').textContent = t; }
566
+ function setProgress(p) { $('progress-fill').style.width = Math.max(0, Math.min(100, p)) + '%'; }
567
+ function fmtTime(ms) { const s = Math.floor(ms / 1000); return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0'); }
568
+
569
+ /* ================= Tabs ================= */
570
+ document.querySelectorAll('nav.tabs button[data-tab]').forEach(b => {
571
+ b.addEventListener('click', () => {
572
+ document.querySelectorAll('nav.tabs button[data-tab]').forEach(x => x.classList.remove('active'));
573
+ document.querySelectorAll('section.tabpage').forEach(x => x.classList.remove('active'));
574
+ b.classList.add('active');
575
+ $('page-' + b.dataset.tab).classList.add('active');
576
+ if (b.dataset.tab === 'conocimiento') { renderMemory(); renderRanking(); }
577
+ if (b.dataset.tab === 'historial') renderLibrary();
578
+ });
579
+ });
580
+
581
+ /* ================= Agentes: UI ================= */
582
+ function renderRoster() {
583
+ const r = $('roster');
584
+ r.innerHTML = '';
585
+ agents.forEach((a, i) => {
586
+ const c = document.createElement('div');
587
+ c.className = 'acard';
588
+ c.innerHTML =
589
+ `<div class="ahead"><div class="avatar" style="background:${avatarBg(a.color)};box-shadow:0 0 10px ${a.color}55">${esc(a.emoji || '🤖')}</div>` +
590
+ `<div><div class="aname">${esc(a.name)}</div><div class="aspec">${esc(a.specialty || 'Generalista')}</div></div></div>` +
591
+ `<div class="apers">${esc(a.system)}</div>` +
592
+ `<div class="act"><button class="btn ghost small" data-edit="${i}">Editar</button>` +
593
+ `<button class="btn danger small" data-del="${i}">Quitar</button></div>`;
594
+ r.appendChild(c);
595
+ });
596
+ r.querySelectorAll('[data-edit]').forEach(b => b.addEventListener('click', () => openAgentEditor(+b.dataset.edit)));
597
+ r.querySelectorAll('[data-del]').forEach(b => b.addEventListener('click', () => deleteAgent(+b.dataset.del)));
598
+ }
599
+ function renderPresets() {
600
+ const g = $('presets');
601
+ g.innerHTML = '';
602
+ PRESETS.forEach(p => {
603
+ const d = document.createElement('div');
604
+ d.className = 'preset';
605
+ d.innerHTML = `<div class="pe">${p.emoji}</div><div class="pn">${esc(p.name)}</div><div class="ps">${esc(p.specialty)}</div>`;
606
+ d.title = 'A\u00f1adir al equipo';
607
+ d.addEventListener('click', () => {
608
+ if (agents.some(a => a.name === p.name)) { setStatus(`${p.name} ya est\u00e1 en el equipo.`); return; }
609
+ agents.push({ name: p.name, emoji: p.emoji, color: p.color, specialty: p.specialty, system: p.system, temp: 0.7, maxTokens: 256 });
610
+ lsSet(K.agents, agents); renderRoster();
611
+ setStatus(`${p.name} se ha unido al equipo (${agents.length} agentes).`);
612
+ });
613
+ g.appendChild(d);
614
+ });
615
+ }
616
+ function renderTemplates() {
617
+ const g = $('templates');
618
+ g.innerHTML = '';
619
+ TEMPLATES.forEach(t => {
620
+ const d = document.createElement('div');
621
+ d.className = 'preset';
622
+ 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>`;
623
+ d.title = 'Aplicar modo, equipo y tema';
624
+ d.addEventListener('click', () => {
625
+ agents = t.agents.map(n => {
626
+ const p = PRESETS.find(x => x.name === n);
627
+ return p ? { name: p.name, emoji: p.emoji, color: p.color, specialty: p.specialty, system: p.system, temp: 0.7, maxTokens: 256 } : null;
628
+ }).filter(Boolean);
629
+ if (agents.length < 2) agents = DEFAULT_AGENTS.slice();
630
+ lsSet(K.agents, agents); renderRoster();
631
+ selectMode(t.mode);
632
+ $('topic').value = t.topic;
633
+ setStatus(`Plantilla «${t.name}» aplicada. Pulsa Iniciar cuando quieras.`);
634
+ document.querySelector('nav.tabs button[data-tab="debate"]').click();
635
+ });
636
+ g.appendChild(d);
637
+ });
638
+ }
639
+ const agentModal = $('agent-modal');
640
+ let editingAgent = -1;
641
+ function openAgentEditor(i) {
642
+ editingAgent = i;
643
+ const a = agents[i] || {};
644
+ $('agent-modal-title').textContent = i >= 0 ? 'Editar agente' : 'Nuevo agente';
645
+ $('agent-delete').style.display = i >= 0 ? 'inline-block' : 'none';
646
+ $('agent-name').value = a.name || '';
647
+ $('agent-emoji').value = a.emoji || '\u{1F916}';
648
+ $('agent-color').value = /^#[0-9a-fA-F]{6}$/.test(a.color || '') ? a.color : '#2dd4bf';
649
+ $('agent-spec').value = a.specialty || '';
650
+ $('agent-system').value = a.system || '';
651
+ $('agent-temp').value = a.temp ?? 0.7;
652
+ $('agent-maxtokens').value = a.maxTokens ?? 256;
653
+ agentModal.classList.add('open');
654
+ $('agent-name').focus();
655
+ }
656
+ function deleteAgent(i) {
657
+ const a = agents[i];
658
+ if (!a) return;
659
+ if (agents.length <= 2) { alert('Se necesitan al menos 2 agentes.'); return; }
660
+ if (!confirm(`\u00bfQuitar a ${a.name} del equipo?`)) return;
661
+ agents.splice(i, 1);
662
+ lsSet(K.agents, agents); renderRoster();
663
+ }
664
+ $('add-agent').addEventListener('click', () => openAgentEditor(-1));
665
+ $('reset-agents').addEventListener('click', () => {
666
+ if (!confirm('\u00bfVolver al equipo base de 3 agentes?')) return;
667
+ agents = DEFAULT_AGENTS.slice(); lsSet(K.agents, agents); renderRoster();
668
+ });
669
+ $('agent-cancel').addEventListener('click', () => agentModal.classList.remove('open'));
670
+ agentModal.addEventListener('click', e => { if (e.target === agentModal) agentModal.classList.remove('open'); });
671
+ $('agent-delete').addEventListener('click', () => { deleteAgent(editingAgent); agentModal.classList.remove('open'); });
672
+ $('agent-save').addEventListener('click', () => {
673
+ const name = $('agent-name').value.trim();
674
+ if (!name) { alert('El nombre no puede estar vac\u00edo.'); return; }
675
+ const system = $('agent-system').value.trim();
676
+ if (!system) { alert('Describe la personalidad del agente.'); return; }
677
+ const data = {
678
+ name, system,
679
+ emoji: $('agent-emoji').value.trim() || '\u{1F916}',
680
+ color: $('agent-color').value,
681
+ specialty: $('agent-spec').value.trim() || 'Generalista',
682
+ temp: Math.min(1.5, Math.max(0, parseFloat($('agent-temp').value) || 0.7)),
683
+ maxTokens: Math.min(1024, Math.max(64, parseInt($('agent-maxtokens').value) || 256)),
684
+ };
685
+ if (editingAgent >= 0) agents[editingAgent] = data; else agents.push(data);
686
+ lsSet(K.agents, agents); renderRoster();
687
+ agentModal.classList.remove('open');
688
+ });
689
+
690
+ /* ================= Modos y temas ================= */
691
+ function selectMode(m) {
692
+ mode = m;
693
+ document.querySelectorAll('.mode-card').forEach(c => c.classList.toggle('sel', c.dataset.mode === m));
694
+ }
695
+ (function renderModes() {
696
+ const g = $('modes');
697
+ Object.entries(MODES).forEach(([key, m]) => {
698
+ const d = document.createElement('div');
699
+ d.className = 'mode-card' + (key === mode ? ' sel' : '');
700
+ d.dataset.mode = key;
701
+ d.innerHTML = `<div class="me">${m.emoji}</div><div class="mn">${m.name}</div><div class="md">${m.desc}</div>`;
702
+ d.addEventListener('click', () => selectMode(key));
703
+ g.appendChild(d);
704
+ });
705
+ })();
706
+ (function fillSuggestions() {
707
+ const sugg = $('topic-sugg');
708
+ const ph = document.createElement('option');
709
+ ph.value = ''; ph.textContent = '\u{1F3B2} Ideas y experimentos\u2026';
710
+ sugg.appendChild(ph);
711
+ [...TOPIC_POOL].sort(() => Math.random() - .5).slice(0, 10).forEach(t => {
712
+ const o = document.createElement('option');
713
+ o.value = t; o.textContent = t.length > 60 ? t.slice(0, 57) + '\u2026' : t;
714
+ sugg.appendChild(o);
715
+ });
716
+ sugg.addEventListener('change', () => {
717
+ if (sugg.value) { $('topic').value = sugg.value; $('topic').focus(); }
718
+ sugg.selectedIndex = 0;
719
+ });
720
+ })();
721
+
722
+ /* ================= Modelo ================= */
723
+ function engineBadge() {
724
+ const el = $('st-engine');
725
+ if (navigator.gpu) { el.textContent = 'WebGPU'; }
726
+ else { el.textContent = 'CPU/WASM (sin WebGPU)'; }
727
+ }
728
+ async function updateStorageStat() {
729
+ try {
730
+ const e = await navigator.storage.estimate();
731
+ if (e && e.quota) $('st-mem').textContent = `${((e.usage || 0) / 1048576).toFixed(0)} MB / ${(e.quota / 1073741824).toFixed(1)} GB`;
732
+ } catch (err) {}
733
+ }
734
+ function setPill(state, txt) {
735
+ const p = $('model-pill');
736
+ p.className = 'model-pill ' + state;
737
+ $('model-pill-txt').textContent = txt;
738
+ }
739
+ async function loadModel(repo, file) {
740
+ const url = CONFIG.modelUrl || `https://huggingface.co/${repo}/resolve/main/${file}`;
741
+ $('start-btn').disabled = true;
742
+ setProgress(0);
743
+ setPill('', 'cargando…');
744
+ setStatus(`Descargando ${file} (ctx ${CONFIG.nCtx})\u2026`);
745
+ const t0 = performance.now();
746
+ try {
747
+ if (wllama) await wllama.exit();
748
+ wllama = new Wllama({
749
+ 'default': 'https://cdn.jsdelivr.net/npm/@wllama/wllama@3.5.1/esm/wasm/wllama.wasm',
750
+ }, { parallelDownloads: 5 });
751
+ await wllama.loadModelFromUrl(url, {
752
+ n_gpu_layers: 999,
753
+ n_ctx: CONFIG.nCtx,
754
+ n_batch: 512,
755
+ n_threads: Math.max(1, Math.min(8, navigator.hardwareConcurrency || 4)),
756
+ progressCallback: ({ loaded, total }) => {
757
+ if (total > 0) {
758
+ const pct = Math.round((loaded / total) * 100);
759
+ setProgress(pct);
760
+ setStatus(`Descargando\u2026 ${pct}% (${(loaded / 1048576).toFixed(0)} MB)`);
761
+ }
762
+ },
763
+ });
764
+ modelLoadMs = performance.now() - t0;
765
+ setProgress(100);
766
+ setPill('ready', file.replace('.gguf', '').slice(0, 34));
767
+ setStatus(`Modelo listo en ${(modelLoadMs / 1000).toFixed(0)} s. ${agents.length} agentes preparados.`);
768
+ $('start-btn').disabled = false;
769
+ $('start-btn').textContent = 'Iniciar debate';
770
+ updateStorageStat();
771
+ } catch (e) {
772
+ console.error(e);
773
+ setPill('error', 'error de carga');
774
+ setStatus('Error al cargar el modelo');
775
+ addSysNote('No se pudo cargar el modelo: ' + (e?.message || e) +
776
+ '. Si la descarga se interrumpi\u00f3 o falta espacio, prueba el bot\u00f3n de limpieza o un modelo m\u00e1s peque\u00f1o en Ajustes.');
777
+ const b = document.createElement('button');
778
+ b.className = 'btn small'; b.style.marginTop = '8px';
779
+ b.textContent = 'Limpiar cach\u00e9 y reintentar';
780
+ b.addEventListener('click', async () => {
781
+ b.disabled = true; b.textContent = 'Limpiando\u2026';
782
+ try {
783
+ if ('caches' in window) for (const k of await caches.keys()) await caches.delete(k);
784
+ if (indexedDB.databases) for (const db of await indexedDB.databases())
785
+ await new Promise(r => { const q = indexedDB.deleteDatabase(db.name); q.onsuccess = q.onerror = q.onblocked = r; });
786
+ if (navigator.storage?.getDirectory) {
787
+ const dir = await navigator.storage.getDirectory().catch(() => null);
788
+ if (dir) for await (const k of dir.keys()) await dir.removeEntry(k, { recursive: true }).catch(() => {});
789
+ }
790
+ } catch (_) {}
791
+ loadModel(repo, file);
792
+ });
793
+ $('chat').appendChild(b);
794
+ }
795
+ }
796
+
797
+ /* ================= Chat UI y estad\u00edsticas ================= */
798
+ const chatEl = $('chat');
799
+ function addMsg(agent, opts = {}) {
800
+ const d = document.createElement('div');
801
+ d.className = 'msg' + (opts.isUser ? ' user' : '') + (opts.kind === 'devil' ? ' devil' : '');
802
+ const content = document.createElement('div');
803
+ content.className = 'content';
804
+ const who = document.createElement('div');
805
+ who.className = 'who';
806
+ const body = document.createElement('div');
807
+ body.className = 'body';
808
+ const meta = document.createElement('div');
809
+ meta.className = 'meta';
810
+ if (opts.isUser) { who.textContent = 'T\u00fa'; who.style.color = 'var(--accent)'; }
811
+ else {
812
+ const av = document.createElement('div');
813
+ av.className = 'avatar';
814
+ av.style.background = avatarBg(agent.color || '#2dd4bf');
815
+ av.style.boxShadow = '0 0 8px ' + (agent.color || '#2dd4bf') + '55';
816
+ av.textContent = agent.emoji || '\u{1F916}';
817
+ d.insertBefore(av, content);
818
+ who.textContent = agent.name;
819
+ who.style.color = agent.color || 'var(--accent)';
820
+ }
821
+ if (opts.role) {
822
+ const rb = document.createElement('span');
823
+ rb.className = 'badge role';
824
+ rb.textContent = opts.role;
825
+ who.appendChild(rb);
826
+ }
827
+ content.appendChild(who); content.appendChild(body); content.appendChild(meta);
828
+ d.appendChild(content);
829
+ chatEl.appendChild(d);
830
+ chatEl.scrollTop = chatEl.scrollHeight;
831
+ return { el: d, body, meta };
832
+ }
833
+ function addSysNote(text) {
834
+ const d = document.createElement('div');
835
+ d.className = 'msg system-note';
836
+ d.innerHTML = `<div class="content"><div class="body">${esc(text)}</div></div>`;
837
+ chatEl.appendChild(d);
838
+ chatEl.scrollTop = chatEl.scrollHeight;
839
+ return d;
840
+ }
841
+ function bumpStats(name, tokens, ms) {
842
+ stats.tokens[name] = (stats.tokens[name] || 0) + tokens;
843
+ stats.turns[name] = (stats.turns[name] || 0) + 1;
844
+ if (ms > 300 && tokens > 2) stats.speeds.push(tokens / (ms / 1000));
845
+ if (stats.speeds.length > 30) stats.speeds.shift();
846
+ $('st-turns').textContent = Object.values(stats.turns).reduce((a, b) => a + b, 0);
847
+ $('st-tokens').textContent = Object.values(stats.tokens).reduce((a, b) => a + b, 0);
848
+ const last = stats.speeds[stats.speeds.length - 1];
849
+ const avg = stats.speeds.length ? stats.speeds.reduce((a, b) => a + b, 0) / stats.speeds.length : 0;
850
+ $('st-speed').textContent = stats.speeds.length ? `${last.toFixed(1)} / ${avg.toFixed(1)} tok/s` : '—';
851
+ const maxTok = Math.max(1, ...Object.values(stats.tokens));
852
+ const box = $('st-agents');
853
+ box.innerHTML = '';
854
+ Object.keys(stats.turns).forEach(n => {
855
+ const a = agents.find(x => x.name === n);
856
+ const color = a ? a.color : 'var(--accent)';
857
+ const row = document.createElement('div');
858
+ row.className = 'agent-stat';
859
+ row.innerHTML = `<div class="avatar" style="background:${avatarBg(color || '#2dd4bf')}">${a ? esc(a.emoji) : '🧑'}</div>` +
860
+ `<div class="nm">${esc(n)}</div><div class="bar"><div style="width:${(stats.tokens[n] / maxTok) * 100}%;background:${color}"></div></div>` +
861
+ `<div class="tk">${stats.turns[n]} turnos \u00b7 ${stats.tokens[n]} tok</div>`;
862
+ box.appendChild(row);
863
+ });
864
+ }
865
+
866
+ /* ================= Motor de generaci\u00f3n ================= */
867
+ const RULES = 'Participas en un laboratorio de razonamiento entre varios agentes. ' +
868
+ 'Responde SOLO con tu intervenci\u00f3n: 2-4 frases directas, en espa\u00f1ol. ' +
869
+ 'No escribas tu nombre ni prefijos como "Nombre:". No repitas lo ya dicho; reacciona a lo anterior. ' +
870
+ 'Si cambias de opini\u00f3n, empieza con "Cambio de postura:". ' +
871
+ 'Si necesitas que otro agente compruebe un dato o razonamiento, escribe al final "SOLICITO REVISION: <qu\u00e9>".';
872
+
873
+ function transcriptText(maxChars) {
874
+ const lines = transcript.map(m => `${m.name || 'Usuario'}${m.role ? ' [' + m.role + ']' : ''}: ${m.text}`);
875
+ let out = lines.join('\n\n');
876
+ let dropped = 0;
877
+ while (out.length > maxChars && lines.length > 3) { lines.splice(1, 1); dropped++; out = lines.join('\n\n'); }
878
+ if (dropped > 0) out = '(se han resumido ' + dropped + ' intervenciones antiguas por l\u00edmite de contexto)\n\n' + out;
879
+ return out;
880
+ }
881
+ function memoryContext() {
882
+ if (!$('mem-inject').checked) return '';
883
+ const mem = lsGet(K.memory, []);
884
+ if (!mem.length) return '';
885
+ const items = mem.slice(0, 5).map(m => `- Sobre «${m.topic}»: ${m.conclusion}`).join('\n');
886
+ return 'Conclusiones de debates anteriores del laboratorio:\n' + items + '\n\n';
887
+ }
888
+
889
+ async function llmCall(messages, maxTokens, temperature, onToken) {
890
+ const t0 = performance.now();
891
+ let answer = '', reasoning = '', count = 0;
892
+ const stream = await wllama.createChatCompletion({
893
+ messages, max_tokens: maxTokens, temperature, stream: true,
894
+ });
895
+ for await (const chunk of stream) {
896
+ if (stopRequested) break;
897
+ const delta = chunk.choices?.[0]?.delta || {};
898
+ const tk = delta.content || '';
899
+ const rs = delta.reasoning_content || '';
900
+ if (rs) { reasoning += rs; if (onToken) onToken('', reasoning); }
901
+ if (tk) { answer += tk; count++; if (onToken) onToken(answer, reasoning); }
902
+ }
903
+ const ms = performance.now() - t0;
904
+ return { answer, reasoning, tokens: count, ms, stopped: stopRequested };
905
+ }
906
+
907
+ async function agentTurn(agent, role, instr) {
908
+ const view = transcriptText(CONFIG.economy ? 4000 : 9000);
909
+ const messages = [
910
+ { role: 'system', content: agent.system + (role ? ` Tu rol en esta fase: ${role}.` : '') + ' ' + RULES },
911
+ { role: 'user', content:
912
+ memoryContext() +
913
+ `Tema del debate: ${topic}\nModo: ${MODES[mode].name}.\n\n` +
914
+ (view ? `Debate hasta ahora:\n${view}\n\n` : 'A\u00fan no hay intervenciones.\n\n') +
915
+ `Ahora hablas t\u00fa, ${agent.name}. ${instr}` },
916
+ ];
917
+ const { el, body, meta } = addMsg(agent, { role });
918
+ el.classList.add('streaming');
919
+ setStatus(`${agent.name} (${role || 'agente'}) est\u00e1 razonando\u2026`);
920
+ let think = null;
921
+ try {
922
+ const r = await llmCall(messages, agent.maxTokens || CONFIG.maxTokens, agent.temp ?? CONFIG.temperature,
923
+ (ans, rs) => {
924
+ if (rs && !think) {
925
+ think = document.createElement('details');
926
+ think.className = 'think';
927
+ think.innerHTML = '<summary>Pensamiento</summary><div class="t"></div>';
928
+ body.parentNode.insertBefore(think, body);
929
+ }
930
+ if (rs && think) think.querySelector('.t').textContent = rs;
931
+ if (ans) body.textContent = ans;
932
+ chatEl.scrollTop = chatEl.scrollHeight;
933
+ });
934
+ el.classList.remove('streaming');
935
+ if (r.stopped) { el.remove(); return false; }
936
+ let answer = r.answer.replace(/^\s*(?:\*\*)?[A-Za-z\u00c0-\u024f]+:\s*/, '').trim();
937
+ if (!answer) { el.remove(); setStatus('Listo'); return true; }
938
+ let reviewReq = null;
939
+ const mRev = /SOLICITO REVISION:\s*(.+?)$/im.exec(answer);
940
+ if (mRev) { reviewReq = mRev[1].trim(); answer = answer.replace(/SOLICITO REVISION:[\s\S]*$/im, '').trim(); }
941
+ const changed = /^cambio de postura/i.test(answer);
942
+ body.innerHTML = (typeof marked !== 'undefined') ? marked.parse(answer) : esc(answer).replace(/\n/g, '<br>');
943
+ if (changed) {
944
+ const c = document.createElement('span');
945
+ c.className = 'chip-change'; c.textContent = '\u{1F504} cambio de postura';
946
+ body.parentNode.querySelector('.who').appendChild(c);
947
+ }
948
+ meta.textContent = `${r.tokens} tokens \u00b7 ${(r.tokens / (r.ms / 1000)).toFixed(1)} tok/s`;
949
+ transcript.push({ name: agent.name, role, text: answer, round: resume.round, tokens: r.tokens, ms: r.ms, changed });
950
+ bumpStats(agent.name, r.tokens, r.ms);
951
+ if (reviewReq && (stats.reviews || 0) < 2) {
952
+ stats.reviews = (stats.reviews || 0) + 1;
953
+ const other = agents.find(a => a.name !== agent.name);
954
+ if (other) {
955
+ addSysNote(`${agent.name} solicita una segunda opini\u00f3n: ${reviewReq}`);
956
+ await agentTurn(other, 'Revisor', `Otro agente pidi\u00f3 que comprobaras esto: «${reviewReq}». Revisa el razonamiento y responde si es correcto.`);
957
+ }
958
+ }
959
+ return true;
960
+ } catch (e) {
961
+ console.error(e);
962
+ el.classList.remove('streaming');
963
+ el.classList.add('err');
964
+ body.textContent = 'Error: ' + (e?.message || e);
965
+ return false;
966
+ }
967
+ }
968
+
969
+ /* ================= Orquestaci\u00f3n por modo ================= */
970
+ function buildSteps(m, round, lastRound) {
971
+ const n = agents.length;
972
+ const steps = [];
973
+ const push = (idx, role, instr) => steps.push({ idx, role, instr });
974
+ if (m === 'adversarial') {
975
+ const roles = [
976
+ ['Proponente', 'Exp\u00f3n o refuerza tu posici\u00f3n con un argumento concreto y defendible.'],
977
+ ['Atacante', 'Encuentra el punto m\u00e1s d\u00e9bil del argumento anterior y at\u00e1calo con precisi\u00f3n.'],
978
+ ['Defensor', 'Defiende la posici\u00f3n atacada: corrige, matiza o reconoce el fallo y mejora el argumento.'],
979
+ ];
980
+ for (let i = 0; i < n; i++) {
981
+ const [role, instr] = roles[(i + round - 1) % 3];
982
+ push(i, role, instr);
983
+ }
984
+ } else if (m === 'consejo') {
985
+ for (let i = 0; i < n; i++)
986
+ push(i, agents[i].specialty || 'Consejero', 'Desde tu perfil, aporta tu an\u00e1lisis para alcanzar una decisi\u00f3n conjunta.');
987
+ const s = (round - 1) % n;
988
+ push(s, 'S\u00edntesis', 'Sintetiza el consejo: resume acuerdos y desacuerdos y prop\u00f3n una decisi\u00f3n conjunta.');
989
+ } else if (m === 'juicio') {
990
+ const jr = ['Fiscal', 'Defensa', 'Juez'];
991
+ for (let i = 0; i < n; i++) {
992
+ if (i % 3 === 0) push(i, 'Fiscal', 'Como fiscal, presenta o refuerza los cargos con argumentos y evidencias.');
993
+ else if (i % 3 === 1) push(i, 'Defensa', 'Como defensa, rebate los cargos y protege tu posici\u00f3n.');
994
+ else push(i, 'Perito', 'Como perito imparcial, aporta valoraci\u00f3n t\u00e9cnica sobre lo dicho por ambas partes.');
995
+ }
996
+ if (lastRound) push((n - 1), 'Juez', 'Como juez, valora las partes y emite un veredicto razonado. Empieza con "VEREDICTO:".');
997
+ } else if (m === 'investigacion') {
998
+ for (let i = 0; i < n; i++) {
999
+ if (round === 1) push(i, 'Hip\u00f3tesis', 'Formula tu hip\u00f3tesis sobre el tema y justif\u00edcala brevemente.');
1000
+ else if (lastRound) push(i, 'Experimento', 'Dise\u00f1a un experimento o prueba concreta para comprobar las conclusiones del debate.');
1001
+ else push(i, 'Contraprueba', 'Busca contradicciones y lagunas en las hip\u00f3tesis de los dem\u00e1s.');
1002
+ }
1003
+ } else if (m === 'resolucion') {
1004
+ for (let i = 0; i < n; i++) {
1005
+ if (round === 1) push(i, 'Propuesta', 'Prop\u00f3n tu soluci\u00f3n al problema, distinta de la de los dem\u00e1s.');
1006
+ 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.');
1007
+ else push(i, 'Comparaci\u00f3n', 'Compara las soluciones propuestas, combina sus puntos fuertes y mejora la tuya.');
1008
+ }
1009
+ }
1010
+ return steps;
1011
+ }
1012
+
1013
+ async function runDebate() {
1014
+ running = true;
1015
+ stopRequested = false;
1016
+ $('start-btn').classList.add('hidden');
1017
+ $('stop-btn').classList.remove('hidden');
1018
+ $('topic').disabled = true;
1019
+ if (!stats.startTs) stats.startTs = Date.now();
1020
+ const timer = setInterval(() => { if (stats.startTs) $('st-time').textContent = fmtTime(Date.now() - stats.startTs); }, 1000);
1021
+ try {
1022
+ for (let r = resume.round; r <= CONFIG.rounds && !stopRequested; r++) {
1023
+ resume.round = r;
1024
+ $('st-round').textContent = `${r}/${CONFIG.rounds}`;
1025
+ setStatus(`Ronda ${r}/${CONFIG.rounds} \u00b7 ${MODES[mode].name}`);
1026
+ const steps = (r === resume.round && resume.steps) ? resume.steps : buildSteps(mode, r, r === CONFIG.rounds);
1027
+ const startIdx = (r === resume.round) ? resume.stepIdx : 0;
1028
+ for (let s = startIdx; s < steps.length; s++) {
1029
+ if (stopRequested) { resume = { round: r, stepIdx: s, steps }; break; }
1030
+ const ok = await agentTurn(agents[steps[s].idx], steps[s].role, steps[s].instr);
1031
+ if (!ok) { if (stopRequested) resume = { round: r, stepIdx: s, steps }; break; }
1032
+ }
1033
+ if (!stopRequested) resume = { round: r + 1, stepIdx: 0, steps: null };
1034
+ else break;
1035
+ }
1036
+ } finally {
1037
+ clearInterval(timer);
1038
+ running = false;
1039
+ $('stop-btn').classList.add('hidden');
1040
+ $('start-btn').classList.remove('hidden');
1041
+ $('start-btn').disabled = false;
1042
+ $('topic').disabled = false;
1043
+ if (stopRequested) {
1044
+ $('start-btn').textContent = 'Continuar debate';
1045
+ setStatus('Pausado. Puedes continuar, intervenir o cambiar de tema.');
1046
+ } else {
1047
+ debateFinished = true;
1048
+ $('start-btn').textContent = 'Nuevo debate';
1049
+ $('devil-btn').disabled = false;
1050
+ $('devil-btn2').disabled = false;
1051
+ $('analyze-btn').disabled = false;
1052
+ setStatus('Debate terminado. Generando an\u00e1lisis\u2026');
1053
+ await runAnalysis(true);
1054
+ }
1055
+ }
1056
+ }
1057
+
1058
+ /* ================= An\u00e1lisis: consenso ================= */
1059
+ async function llmSimple(system, user, maxTokens) {
1060
+ const r = await llmCall(
1061
+ [{ role: 'system', content: system }, { role: 'user', content: user }],
1062
+ maxTokens, 0.3, null);
1063
+ return r;
1064
+ }
1065
+ function analysisNote(text) {
1066
+ const d = document.createElement('div');
1067
+ d.className = 'phase-note';
1068
+ d.innerHTML = `<span class="spin">\u23F3</span><span>${esc(text)}</span>`;
1069
+ $('analysis-out').appendChild(d);
1070
+ return d;
1071
+ }
1072
+ function doneNote(d, text) { d.innerHTML = `<span>\u2705</span><span>${esc(text)}</span>`; }
1073
+
1074
+ async function runConsensus() {
1075
+ const note = analysisNote('Buscando consenso din\u00e1mico\u2026');
1076
+ const view = transcriptText(5000);
1077
+ const synth = await llmSimple(
1078
+ 'Eres un sintetizador neutral. Redacta conclusiones claras y breves.',
1079
+ `Tema: ${topic}\n\nDebate:\n${view}\n\nRedacta la conclusi\u00f3n final del debate en 3-5 frases, sin adornos.`,
1080
+ 220);
1081
+ const conclusion = synth.answer.trim() || 'Sin conclusi\u00f3n clara.';
1082
+ const votes = [];
1083
+ for (const a of agents) {
1084
+ if (stopRequested) break;
1085
+ setStatus(`Votaci\u00f3n de consenso: ${a.name}\u2026`);
1086
+ const v = await llmSimple(
1087
+ a.system + ' Debes valorar una conclusi\u00f3n. Responde EXACTAMENTE en este formato:\nVOTO: SI\nRAZON: <una frase>',
1088
+ `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.`,
1089
+ 90);
1090
+ const m = /VOTO:\s*(SI|S\u00cd|PARCIAL|NO)/i.exec(v.answer);
1091
+ const razon = (/\nRAZON:\s*(.+)/i.exec(v.answer) || [])[1] || '';
1092
+ votes.push({ name: a.name, vote: m ? m[1].toUpperCase().replace('\u00cd', 'I') : 'PARCIAL', reason: razon.trim() });
1093
+ }
1094
+ const si = votes.filter(v => v.vote === 'SI').length;
1095
+ const no = votes.filter(v => v.vote === 'NO').length;
1096
+ let status, cls, icon;
1097
+ if (votes.length && si === votes.length) { status = 'Consenso alcanzado'; cls = 'ok'; icon = '\u{1F7E2}'; }
1098
+ else if (si + votes.filter(v => v.vote === 'PARCIAL').length >= Math.ceil(votes.length / 2) && no === 0) { status = 'Consenso parcial'; cls = 'partial'; icon = '\u{1F7E1}'; }
1099
+ else { status = 'Desacuerdo fundamentado'; cls = 'disagree'; icon = '\u{1F534}'; }
1100
+ doneNote(note, 'Consenso evaluado: ' + status);
1101
+ return { conclusion, votes, status, cls, icon };
1102
+ }
1103
+
1104
+ /* ================= An\u00e1lisis: evaluador ================= */
1105
+ const CRITERIA = [
1106
+ ['ARGUMENTOS', 'Calidad de argumentos'],
1107
+ ['COHERENCIA', 'Coherencia l\u00f3gica'],
1108
+ ['DETECCION', 'Detecci\u00f3n de errores'],
1109
+ ['EVIDENCIA', 'Evidencia y justificaci\u00f3n'],
1110
+ ['INCERTIDUMBRE', 'Reconoce incertidumbre'],
1111
+ ['CONCLUSION', 'Calidad de conclusi\u00f3n'],
1112
+ ];
1113
+ async function runEvaluation() {
1114
+ const note = analysisNote('Evaluador analizando intervenciones\u2026');
1115
+ const view = transcriptText(4500);
1116
+ const names = agents.map(a => a.name).join(', ');
1117
+ const prompt =
1118
+ `Tema: ${topic}\n\nDebate:\n${view}\n\n` +
1119
+ `Eval\u00faa a cada agente (${names}) de 0 a 10 en cada criterio. Responde EXACTAMENTE con este formato, repitiendo el bloque por agente:\n` +
1120
+ `AGENTE: <nombre>\nARGUMENTOS: <0-10>\nCOHERENCIA: <0-10>\nDETECCION: <0-10>\nEVIDENCIA: <0-10>\nINCERTIDUMBRE: <0-10>\nCONCLUSION: <0-10>\nCOMENTARIO: <una frase que justifique la puntuaci\u00f3n>\n\n` +
1121
+ `Al final a\u00f1ade:\nRELACIONES: <qui\u00e9n apoya o contradice a qui\u00e9n, ej: Ada apoya a Bruno; Bruno contradice a Carla; o NINGUNA>\n` +
1122
+ `CONTRADICCIONES: <contradicciones detectadas entre agentes o NINGUNA>\n` +
1123
+ `FALACIAS: <falacias l\u00f3gicas detectadas o NINGUNA>\n` +
1124
+ `SIN_JUSTIFICAR: <afirmaciones sin justificar o NINGUNA>`;
1125
+ const r = await llmSimple(
1126
+ 'Eres un evaluador de debates. Punt\u00faas con criterio, explicas cada puntuaci\u00f3n y no premias solo al m\u00e1s convincente: premias rigor, evidencia y honestidad intelectual.',
1127
+ prompt, 700);
1128
+ const blocks = [];
1129
+ const re = /AGENTE:\s*([^\n]+)\n([\s\S]*?)(?=\nAGENTE:|$)/g;
1130
+ let m;
1131
+ while ((m = re.exec(r.answer)) !== null) {
1132
+ const name = m[1].trim().replace(/\*+/g, '');
1133
+ if (!agents.some(a => a.name.toLowerCase() === name.toLowerCase())) continue;
1134
+ const blk = m[2];
1135
+ const scores = {};
1136
+ CRITERIA.forEach(([key]) => {
1137
+ const mm = new RegExp(key + ':\\s*(\\d{1,2})').exec(blk);
1138
+ scores[key] = mm ? Math.min(10, parseInt(mm[1])) : null;
1139
+ });
1140
+ const comment = (/COMENTARIO:\s*([^\n]+)/.exec(blk) || [])[1] || '';
1141
+ const present = Object.values(scores).filter(v => v !== null);
1142
+ const total = present.length ? Math.round((present.reduce((a, b) => a + b, 0) / present.length) * 10) : null;
1143
+ blocks.push({ name, scores, comment: comment.trim(), total });
1144
+ }
1145
+ const grab = k => {
1146
+ const mm = new RegExp(k + ':\\s*([\\s\\S]*?)(?=\\n(?:RELACIONES|CONTRADICCIONES|FALACIAS|SIN_JUSTIFICAR):|$)').exec(r.answer);
1147
+ const v = mm ? mm[1].trim() : '';
1148
+ return /^NINGUNA/i.test(v) ? '' : v;
1149
+ };
1150
+ const relations = grab('RELACIONES');
1151
+ const extra = {
1152
+ contradicciones: grab('CONTRADICCIONES'),
1153
+ falacias: grab('FALACIAS'),
1154
+ sinJustificar: grab('SIN_JUSTIFICAR'),
1155
+ };
1156
+ doneNote(note, `Evaluaci\u00f3n completada (${blocks.length} agentes).`);
1157
+ return { blocks, relations, extra, raw: r.answer };
1158
+ }
1159
+
1160
+ /* ================= An\u00e1lisis: mapa de argumentos ================= */
1161
+ async function runArgMap() {
1162
+ const note = analysisNote('Extrayendo mapa de argumentos\u2026');
1163
+ const view = transcriptText(4500);
1164
+ const r = await llmSimple(
1165
+ '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>',
1166
+ `Tema: ${topic}\n\nDebate:\n${view}`, 320);
1167
+ const lines = r.answer.split('\n').map(l => l.trim()).filter(Boolean);
1168
+ const map = { tesis: [], evid: [], obj: [], concl: [] };
1169
+ let cur = null;
1170
+ for (const l of lines) {
1171
+ const mm = /^(TESIS|EVIDENCIA|OBJECCION|CONCLUSION):\s*(.+)$/.exec(l);
1172
+ if (mm) {
1173
+ cur = mm[1] === 'TESIS' ? 'tesis' : mm[1] === 'EVIDENCIA' ? 'evid' : mm[1] === 'OBJECCION' ? 'obj' : 'concl';
1174
+ map[cur].push(mm[2].trim());
1175
+ } else if (cur && map[cur].length < 4 && !/^(AGENTE|RELACIONES)/.test(l)) map[cur].push(l);
1176
+ }
1177
+ doneNote(note, 'Mapa de argumentos extra\u00eddo.');
1178
+ return map;
1179
+ }
1180
+
1181
+ /* ================= Devil's Advocate ================= */
1182
+ async function runDevil() {
1183
+ if (!wllama || !analysis || !analysis.consensus) return;
1184
+ const devil = { name: "Devil's Advocate", emoji: '\u{1F47F}', color: '#f87171' };
1185
+ document.querySelector('nav.tabs button[data-tab="debate"]').click();
1186
+ 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.)');
1187
+ const { el, body, meta } = addMsg(devil, { role: 'Abogado del diablo' });
1188
+ el.classList.add('streaming');
1189
+ setStatus('El Devil\u2019s Advocate prepara su ataque\u2026');
1190
+ const view = transcriptText(4000);
1191
+ const messages = [
1192
+ { 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.' },
1193
+ { role: 'user', content: `Tema: ${topic}\n\nConclusi\u00f3n del debate:\n${analysis.consensus.conclusion}\n\nDebate (extracto):\n${view}\n\nAtaca la conclusi\u00f3n.` },
1194
+ ];
1195
+ try {
1196
+ const r = await llmCall(messages, 320, 0.85, (ans) => { body.textContent = ans; chatEl.scrollTop = chatEl.scrollHeight; });
1197
+ el.classList.remove('streaming');
1198
+ const text = r.answer.trim();
1199
+ body.innerHTML = (typeof marked !== 'undefined') ? marked.parse(text) : esc(text);
1200
+ meta.textContent = `${r.tokens} tokens \u00b7 ${(r.tokens / (r.ms / 1000)).toFixed(1)} tok/s`;
1201
+ transcript.push({ name: devil.name, role: 'Abogado del diablo', text, round: 'DA', tokens: r.tokens, ms: r.ms, kind: 'devil' });
1202
+ analysis.devil = text;
1203
+ setStatus('El Devil\u2019s Advocate ha hablado. \u00bfResiste la conclusi\u00f3n?');
1204
+ } catch (e) {
1205
+ el.classList.remove('streaming'); el.classList.add('err');
1206
+ body.textContent = 'Error: ' + (e?.message || e);
1207
+ }
1208
+ }
1209
+
1210
+ /* ================= An\u00e1lisis: orquestaci\u00f3n y render ================= */
1211
+ async function runAnalysis(auto) {
1212
+ if (!wllama || !transcript.length) return;
1213
+ $('analyze-btn').disabled = true;
1214
+ $('analysis-empty').classList.add('hidden');
1215
+ $('analysis-out').innerHTML = '';
1216
+ document.querySelector('nav.tabs button[data-tab="analisis"]').click();
1217
+ try {
1218
+ const consensus = await runConsensus();
1219
+ const evaluation = await runEvaluation();
1220
+ const argmap = await runArgMap();
1221
+ analysis = { consensus, evaluation, argmap, devil: analysis?.devil || null, ts: Date.now() };
1222
+ renderAnalysis();
1223
+ saveToLibrary();
1224
+ saveToMemory(consensus);
1225
+ updateRanking(evaluation);
1226
+ setStatus('An\u00e1lisis completado. Puedes invocar al Devil\u2019s Advocate.');
1227
+ if (auto) await runDevil();
1228
+ } catch (e) {
1229
+ console.error(e);
1230
+ addSysNote('Error durante el an\u00e1lisis: ' + (e?.message || e));
1231
+ setStatus('An\u00e1lisis interrumpido.');
1232
+ } finally {
1233
+ $('analyze-btn').disabled = false;
1234
+ }
1235
+ }
1236
+
1237
+ function renderAnalysis() {
1238
+ if (!analysis) return;
1239
+ const out = $('analysis-out');
1240
+ $('analysis-empty').classList.add('hidden');
1241
+ const c = analysis.consensus;
1242
+ const e = analysis.evaluation;
1243
+ const am = analysis.argmap;
1244
+ let html = '';
1245
+ // --- Consenso ---
1246
+ html += `<div class="consensus-hero ${c.cls}"><div class="ci">${c.icon}</div><div>` +
1247
+ `<div class="cs">${esc(c.status)}</div>` +
1248
+ `<div class="muted">Conclusi\u00f3n: ${esc(c.conclusion)}</div></div></div>`;
1249
+ html += `<div class="panel" style="background:var(--panel2)"><h3>\u{1F5F3}\uFE0F Votaci\u00f3n de los agentes</h3><div class="vote-list">`;
1250
+ c.votes.forEach(v => {
1251
+ const cls = v.vote === 'SI' ? 'si' : v.vote === 'NO' ? 'no' : 'parcial';
1252
+ html += `<div class="vrow"><span class="vv ${cls}">${v.vote}</span><span><b>${esc(v.name)}</b>${v.reason ? ' — ' + esc(v.reason) : ''}</span></div>`;
1253
+ });
1254
+ html += '</div>';
1255
+ if (c.cls !== 'ok') {
1256
+ const reasons = c.votes.filter(v => v.vote !== 'SI' && v.reason);
1257
+ if (reasons.length) html += `<div class="muted" style="margin-top:8px"><b style="color:var(--text)">Por qu\u00e9 no hay acuerdo:</b> ` +
1258
+ reasons.map(v => `${esc(v.name)}: ${esc(v.reason)}`).join(' \u00b7 ') + '</div>';
1259
+ }
1260
+ html += '</div>';
1261
+ // --- Puntuaciones ---
1262
+ if (e && e.blocks.length) {
1263
+ html += `<h3 style="margin-top:16px;color:var(--accent);font-size:13px;letter-spacing:1px">EVALUACI\u00d3N DEL DEBATE (orientativa)</h3><div class="score-grid">`;
1264
+ [...e.blocks].sort((a, b) => (b.total ?? 0) - (a.total ?? 0)).forEach(b => {
1265
+ const a = agents.find(x => x.name.toLowerCase() === b.name.toLowerCase());
1266
+ html += `<div class="scard"><div class="stop">` +
1267
+ `<div class="avatar" style="background:${avatarBg(a?.color || '#2dd4bf')}">${esc(a?.emoji || '\u{1F916}')}</div>` +
1268
+ `<div><div class="aname">${esc(b.name)}</div><div class="aspec">${esc(a?.specialty || '')}</div></div>` +
1269
+ `<div class="big">${b.total ?? '?'}<span style="font-size:13px;color:var(--muted)">/100</span></div></div><div class="crit">`;
1270
+ CRITERIA.forEach(([key, label]) => {
1271
+ const v = b.scores[key];
1272
+ html += `<div class="crow"><span class="lb">${label}</span>` +
1273
+ `<span class="bar"><div style="width:${v !== null ? v * 10 : 0}%"></div></span>` +
1274
+ `<span class="vl">${v !== null ? v : '—'}</span></div>`;
1275
+ });
1276
+ if (b.comment) html += `<div class="comment">\u00ab${esc(b.comment)}\u00bb</div>`;
1277
+ html += '</div></div>';
1278
+ });
1279
+ html += '</div>';
1280
+ if (e.relations) {
1281
+ html += `<h3 style="margin-top:14px;color:var(--accent);font-size:13px;letter-spacing:1px">MAPA DE RELACIONES</h3><div class="relchips">`;
1282
+ e.relations.split(';').map(x => x.trim()).filter(Boolean).forEach(rel => {
1283
+ const cls = /contradice|ataca|rebate/i.test(rel) ? 'con' : 'sup';
1284
+ html += `<span class="relchip ${cls}">${esc(rel)}</span>`;
1285
+ });
1286
+ html += '</div>';
1287
+ }
1288
+ const extras = [];
1289
+ if (e.extra.contradicciones) extras.push(['\u{1F500} Contradicciones', e.extra.contradicciones]);
1290
+ if (e.extra.falacias) extras.push(['\u26A0\uFE0F Falacias l\u00f3gicas', e.extra.falacias]);
1291
+ if (e.extra.sinJustificar) extras.push(['\u2753 Afirmaciones sin justificar', e.extra.sinJustificar]);
1292
+ if (extras.length) {
1293
+ html += `<h3 style="margin-top:14px;color:var(--accent);font-size:13px;letter-spacing:1px">DETECTORES</h3>`;
1294
+ extras.forEach(([t, v]) => {
1295
+ 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>`;
1296
+ });
1297
+ }
1298
+ }
1299
+ // --- Mapa de argumentos ---
1300
+ if (am && (am.tesis.length || am.evid.length || am.obj.length || am.concl.length)) {
1301
+ html += `<h3 style="margin-top:16px;color:var(--accent);font-size:13px;letter-spacing:1px">MAPA DE ARGUMENTOS</h3><div class="argmap">`;
1302
+ const col = (cls, title, items) => {
1303
+ let h = `<div class="argcol ${cls}"><h4>${title}</h4>`;
1304
+ items.slice(0, 4).forEach(i => { h += `<div class="argnode">${esc(i)}</div>`; });
1305
+ return h + '</div>';
1306
+ };
1307
+ html += col('tesis', 'Tesis', am.tesis) + col('evid', 'Evidencias', am.evid) +
1308
+ col('obj', 'Objeciones', am.obj) + col('concl', 'Conclusi\u00f3n', am.concl);
1309
+ html += '</div>';
1310
+ }
1311
+ // --- Evoluci\u00f3n de posturas ---
1312
+ html += `<h3 style="margin-top:16px;color:var(--accent);font-size:13px;letter-spacing:1px">EVOLUCI\u00d3N DE POSTURAS</h3><div class="timeline">`;
1313
+ for (let r = 1; r <= CONFIG.rounds; r++) {
1314
+ const items = transcript.filter(t => t.round === r);
1315
+ if (!items.length) continue;
1316
+ html += `<div class="tl-round"><h4>Ronda ${r}</h4>`;
1317
+ items.forEach(t => {
1318
+ html += `<div class="tl-item"><span class="who">${esc(t.name)}${t.changed ? ' \u{1F504}' : ''}</span>` +
1319
+ `<span class="what">${esc(t.text.slice(0, 140))}${t.text.length > 140 ? '\u2026' : ''}</span></div>`;
1320
+ });
1321
+ html += '</div>';
1322
+ }
1323
+ html += '</div>';
1324
+ if (analysis.devil) {
1325
+ html += `<h3 style="margin-top:16px;color:var(--red);font-size:13px;letter-spacing:1px">\u{1F47F} DEVIL'S ADVOCATE</h3>` +
1326
+ `<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></div>`;
1327
+ }
1328
+ out.innerHTML = html;
1329
+ }
1330
+
1331
+ /* ================= Persistencia ================= */
1332
+ function saveToLibrary() {
1333
+ const lib = lsGet(K.library, []);
1334
+ lib.unshift({
1335
+ id: Date.now(), topic, mode, modeName: MODES[mode].name, ts: Date.now(),
1336
+ agents: agents.map(a => ({ name: a.name, emoji: a.emoji, color: a.color, specialty: a.specialty })),
1337
+ transcript, consensus: analysis.consensus, evaluation: analysis.evaluation,
1338
+ argmap: analysis.argmap, devil: analysis.devil,
1339
+ stats: { tokens: stats.tokens, turns: stats.turns },
1340
+ });
1341
+ lsSet(K.library, lib.slice(0, 25));
1342
+ }
1343
+ function saveToMemory(consensus) {
1344
+ if (!consensus || !consensus.conclusion) return;
1345
+ const mem = lsGet(K.memory, []);
1346
+ mem.unshift({ topic, conclusion: consensus.conclusion, status: consensus.status, ts: Date.now() });
1347
+ lsSet(K.memory, mem.slice(0, 12));
1348
+ }
1349
+ function updateRanking(evaluation) {
1350
+ if (!evaluation || !evaluation.blocks) return;
1351
+ const rank = lsGet(K.ranking, {});
1352
+ evaluation.blocks.forEach(b => {
1353
+ if (b.total === null) return;
1354
+ const r = rank[b.name] || { total: 0, n: 0 };
1355
+ rank[b.name] = { total: r.total + b.total, n: r.n + 1 };
1356
+ });
1357
+ lsSet(K.ranking, rank);
1358
+ }
1359
+
1360
+ /* ================= Conocimiento ================= */
1361
+ $('mem-inject').checked = !!lsGet(K.meminject, false);
1362
+ $('mem-inject').addEventListener('change', () => lsSet(K.meminject, $('mem-inject').checked));
1363
+ function renderMemory() {
1364
+ const mem = lsGet(K.memory, []);
1365
+ const el = $('mem-list');
1366
+ el.innerHTML = mem.length ? '' : '<div class="muted">Sin conclusiones guardadas todav\u00eda.</div>';
1367
+ mem.forEach((m, i) => {
1368
+ const d = document.createElement('div');
1369
+ d.className = 'mem-item';
1370
+ d.innerHTML = `<div class="mt">${esc(m.topic)}</div>` +
1371
+ `<div class="mm">${new Date(m.ts).toLocaleString('es-ES')} \u00b7 ${esc(m.status || '')}</div>` +
1372
+ `<div class="mc">${esc(m.conclusion)}</div>` +
1373
+ `<div class="act" style="margin-top:7px"><button class="btn danger small" data-i="${i}">Eliminar</button></div>`;
1374
+ el.appendChild(d);
1375
+ });
1376
+ el.querySelectorAll('[data-i]').forEach(b => b.addEventListener('click', () => {
1377
+ const mem2 = lsGet(K.memory, []); mem2.splice(+b.dataset.i, 1); lsSet(K.memory, mem2); renderMemory();
1378
+ }));
1379
+ }
1380
+ $('mem-clear').addEventListener('click', () => {
1381
+ if (confirm('\u00bfVaciar la memoria de debates?')) { lsSet(K.memory, []); renderMemory(); }
1382
+ });
1383
+ function renderRanking() {
1384
+ const rank = lsGet(K.ranking, {});
1385
+ const rows = Object.entries(rank).map(([name, r]) => ({ name, avg: r.total / r.n, n: r.n }))
1386
+ .sort((a, b) => b.avg - a.avg);
1387
+ const el = $('ranking-out');
1388
+ if (!rows.length) { el.innerHTML = '<div class="muted">Sin puntuaciones acumuladas todav\u00eda.</div>'; return; }
1389
+ let html = '<table class="rank-table"><tr><th>#</th><th>Agente</th><th>Media</th><th>Debates</th></tr>';
1390
+ rows.forEach((r, i) => {
1391
+ 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>`;
1392
+ });
1393
+ el.innerHTML = html + '</table>';
1394
+ }
1395
+
1396
+ /* ================= Historial / biblioteca ================= */
1397
+ function renderLibrary(filter) {
1398
+ const lib = lsGet(K.library, []);
1399
+ const q = (filter ?? $('lib-search').value).trim().toLowerCase();
1400
+ const el = $('lib-list');
1401
+ el.innerHTML = '';
1402
+ const items = lib.filter(it => !q ||
1403
+ it.topic.toLowerCase().includes(q) || it.modeName.toLowerCase().includes(q) ||
1404
+ it.agents.some(a => a.name.toLowerCase().includes(q)));
1405
+ if (!items.length) { el.innerHTML = '<div class="muted">No hay debates guardados. Se guardan autom\u00e1ticamente al terminar el an\u00e1lisis.</div>'; return; }
1406
+ items.forEach(it => {
1407
+ const d = document.createElement('div');
1408
+ d.className = 'lib-item';
1409
+ const status = it.consensus ? it.consensus.status : 'sin an\u00e1lisis';
1410
+ d.innerHTML = `<div class="mt">${esc(it.topic)}</div>` +
1411
+ `<div class="mm">${MODES[it.mode]?.emoji || ''} ${esc(it.modeName)} \u00b7 ${new Date(it.ts).toLocaleString('es-ES')} \u00b7 ` +
1412
+ `${it.agents.map(a => esc(a.name)).join(', ')} \u00b7 ${esc(status)}</div>` +
1413
+ `<div class="actions">` +
1414
+ `<button class="btn small" data-open="${it.id}">Reabrir</button>` +
1415
+ `<button class="btn ghost small" data-replay="${it.id}">\u23EA Replay</button>` +
1416
+ `<button class="btn ghost small" data-md="${it.id}">Markdown</button>` +
1417
+ `<button class="btn ghost small" data-json="${it.id}">JSON</button>` +
1418
+ `<button class="btn ghost small" data-html="${it.id}">HTML</button>` +
1419
+ `<button class="btn danger small" data-del="${it.id}">Eliminar</button></div>`;
1420
+ el.appendChild(d);
1421
+ });
1422
+ el.querySelectorAll('[data-open]').forEach(b => b.addEventListener('click', () => reopenDebate(+b.dataset.open)));
1423
+ el.querySelectorAll('[data-replay]').forEach(b => b.addEventListener('click', () => replayDebate(+b.dataset.replay)));
1424
+ el.querySelectorAll('[data-md]').forEach(b => b.addEventListener('click', () => exportDebate(+b.dataset.md, 'md')));
1425
+ el.querySelectorAll('[data-json]').forEach(b => b.addEventListener('click', () => exportDebate(+b.dataset.json, 'json')));
1426
+ el.querySelectorAll('[data-html]').forEach(b => b.addEventListener('click', () => exportDebate(+b.dataset.html, 'html')));
1427
+ el.querySelectorAll('[data-del]').forEach(b => b.addEventListener('click', () => {
1428
+ if (!confirm('\u00bfEliminar este debate de la biblioteca?')) return;
1429
+ lsSet(K.library, lsGet(K.library, []).filter(x => x.id !== +b.dataset.del));
1430
+ renderLibrary();
1431
+ }));
1432
+ }
1433
+ $('lib-search').addEventListener('input', () => renderLibrary());
1434
+ $('lib-clear').addEventListener('click', () => {
1435
+ if (confirm('\u00bfBorrar toda la biblioteca de debates?')) { lsSet(K.library, []); renderLibrary(); }
1436
+ });
1437
+
1438
+ function reopenDebate(id) {
1439
+ const it = lsGet(K.library, []).find(x => x.id === id);
1440
+ if (!it) return;
1441
+ topic = it.topic; mode = it.mode;
1442
+ $('topic').value = it.topic;
1443
+ selectMode(it.mode);
1444
+ transcript = it.transcript.slice();
1445
+ chatEl.innerHTML = '';
1446
+ transcript.forEach(t => renderHistoric(t));
1447
+ resume = { round: CONFIG.rounds, stepIdx: 0, steps: null };
1448
+ analysis = it.consensus ? { consensus: it.consensus, evaluation: it.evaluation, argmap: it.argmap, devil: it.devil, ts: it.ts } : null;
1449
+ debateFinished = true;
1450
+ $('devil-btn').disabled = false; $('devil-btn2').disabled = false; $('analyze-btn').disabled = false;
1451
+ $('start-btn').textContent = 'Continuar debate';
1452
+ document.querySelector('nav.tabs button[data-tab="debate"]').click();
1453
+ if (analysis) renderAnalysis();
1454
+ setStatus(`Debate reabierto: ${it.agents.length} agentes, ${transcript.length} intervenciones. Puedes continuar.`);
1455
+ }
1456
+ function renderHistoric(t) {
1457
+ const a = agents.find(x => x.name === t.name) ||
1458
+ (t.kind === 'devil' ? { name: t.name, emoji: '\u{1F47F}', color: '#f87171' } :
1459
+ { name: t.name || 'Usuario', emoji: '\u{1F9D1}', color: '#2dd4bf' });
1460
+ const { body } = t.isUser ? addMsg(null, { isUser: true }) : addMsg(a, { role: t.role, kind: t.kind });
1461
+ body.innerHTML = (typeof marked !== 'undefined') ? marked.parse(t.text) : esc(t.text);
1462
+ }
1463
+ let replayTimer = null;
1464
+ function replayDebate(id) {
1465
+ const it = lsGet(K.library, []).find(x => x.id === id);
1466
+ if (!it) return;
1467
+ document.querySelector('nav.tabs button[data-tab="debate"]').click();
1468
+ chatEl.innerHTML = '';
1469
+ addSysNote(`\u23EA Replay: ${it.topic} (${it.transcript.length} turnos)`);
1470
+ let i = 0;
1471
+ clearInterval(replayTimer);
1472
+ replayTimer = setInterval(() => {
1473
+ if (i >= it.transcript.length) { clearInterval(replayTimer); addSysNote('Fin del replay.'); return; }
1474
+ const t = it.transcript[i++];
1475
+ const a = (it.agents.find(x => x.name === t.name)) ||
1476
+ { name: t.name || 'Usuario', emoji: t.kind === 'devil' ? '\u{1F47F}' : '\u{1F9D1}', color: t.kind === 'devil' ? '#f87171' : '#2dd4bf' };
1477
+ const { body } = t.isUser ? addMsg(null, { isUser: true }) : addMsg(a, { role: t.role, kind: t.kind });
1478
+ body.innerHTML = (typeof marked !== 'undefined') ? marked.parse(t.text) : esc(t.text);
1479
+ }, 1100);
1480
+ }
1481
+
1482
+ /* ================= Exportaci\u00f3n ================= */
1483
+ function download(name, content, type) {
1484
+ const a = document.createElement('a');
1485
+ a.href = URL.createObjectURL(new Blob([content], { type }));
1486
+ a.download = name;
1487
+ a.click();
1488
+ setTimeout(() => URL.revokeObjectURL(a.href), 5000);
1489
+ }
1490
+ function debateMarkdown(it) {
1491
+ let md = `# ${it.topic}\n\n**Modo:** ${it.modeName} · **Fecha:** ${new Date(it.ts).toLocaleString('es-ES')} · ` +
1492
+ `**Agentes:** ${it.agents.map(a => a.name).join(', ')}\n\n`;
1493
+ if (it.consensus) md += `## ${it.consensus.icon || ''} ${it.consensus.status}\n\n${it.consensus.conclusion}\n\n` +
1494
+ it.consensus.votes.map(v => `- **${v.name}: ${v.vote}**${v.reason ? ' — ' + v.reason : ''}`).join('\n') + '\n\n';
1495
+ md += '## Transcripci\u00f3n\n\n';
1496
+ it.transcript.forEach(t => { md += `**${t.name || 'Usuario'}**${t.role ? ' [' + t.role + ']' : ''}:\n${t.text}\n\n`; });
1497
+ if (it.evaluation && it.evaluation.blocks) {
1498
+ md += '## Evaluaci\u00f3n (orientativa, mismo modelo)\n\n';
1499
+ it.evaluation.blocks.forEach(b => {
1500
+ md += `### ${b.name}: ${b.total ?? '?'}/100\n`;
1501
+ CRITERIA.forEach(([k, l]) => { md += `- ${l}: ${b.scores[k] ?? '—'}/10\n`; });
1502
+ if (b.comment) md += `> ${b.comment}\n`;
1503
+ md += '\n';
1504
+ });
1505
+ }
1506
+ if (it.devil) md += `## \u{1F47F} Devil's Advocate\n\n${it.devil}\n`;
1507
+ md += '\n---\nGenerado por Multi-Agent Lab (WebGPU, modelo local). Evaluaciones orientativas, no objetivas.\n';
1508
+ return md;
1509
+ }
1510
+ function debateHTML(it) {
1511
+ const md = debateMarkdown(it);
1512
+ const bodyHtml = (typeof marked !== 'undefined') ? marked.parse(md) : '<pre>' + esc(md) + '</pre>';
1513
+ return `<!DOCTYPE html><html lang="es"><head><meta charset="utf-8"><title>${esc(it.topic)}</title>` +
1514
+ `<style>body{font-family:system-ui;max-width:760px;margin:30px auto;padding:0 16px;line-height:1.6;color:#111}</style></head>` +
1515
+ `<body>${bodyHtml}</body></html>`;
1516
+ }
1517
+ function exportDebate(id, fmt) {
1518
+ const it = lsGet(K.library, []).find(x => x.id === id);
1519
+ if (!it) return;
1520
+ const base = 'debate-' + new Date(it.ts).toISOString().slice(0, 10) + '-' + it.id;
1521
+ if (fmt === 'md') download(base + '.md', debateMarkdown(it), 'text/markdown');
1522
+ else if (fmt === 'json') download(base + '.json', JSON.stringify(it, null, 2), 'application/json');
1523
+ else if (fmt === 'html') download(base + '.html', debateHTML(it), 'text/html');
1524
+ }
1525
+
1526
+ /* ================= Controles principales ================= */
1527
+ function startFresh(newTopic) {
1528
+ topic = newTopic;
1529
+ transcript = [];
1530
+ chatEl.innerHTML = '';
1531
+ stats = { tokens: {}, turns: {}, speeds: [], startTs: 0, reviews: 0 };
1532
+ ['st-turns', 'st-tokens'].forEach(id => $(id).textContent = '0');
1533
+ $('st-speed').textContent = '—'; $('st-time').textContent = '0:00'; $('st-agents').innerHTML = '';
1534
+ resume = { round: 1, stepIdx: 0, steps: null };
1535
+ analysis = null;
1536
+ debateFinished = false;
1537
+ $('analysis-out').innerHTML = '';
1538
+ $('analysis-empty').classList.remove('hidden');
1539
+ $('devil-btn').disabled = true; $('devil-btn2').disabled = true; $('analyze-btn').disabled = true;
1540
+ const m = addMsg(null, { isUser: true });
1541
+ m.body.textContent = newTopic;
1542
+ transcript.push({ name: null, role: 'Tema', text: 'Tema propuesto: ' + newTopic, round: 0, isUser: true });
1543
+ }
1544
+ $('start-btn').addEventListener('click', () => {
1545
+ if (!wllama || running) return;
1546
+ const newTopic = $('topic').value.trim();
1547
+ if (newTopic && newTopic !== topic) startFresh(newTopic);
1548
+ else if (!topic) { $('topic').focus(); setStatus('Escribe un tema para debatir.'); return; }
1549
+ runDebate();
1550
+ });
1551
+ $('stop-btn').addEventListener('click', () => { stopRequested = true; setStatus('Pausando\u2026'); });
1552
+ $('topic').addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); $('start-btn').click(); } });
1553
+ function interject() {
1554
+ const txt = $('interject-txt').value.trim();
1555
+ if (!txt) return;
1556
+ if (!topic) { setStatus('Primero inicia un debate.'); return; }
1557
+ const m = addMsg(null, { isUser: true });
1558
+ m.body.textContent = txt;
1559
+ transcript.push({ name: null, role: 'Intervenci\u00f3n', text: txt, round: resume.round, isUser: true });
1560
+ $('interject-txt').value = '';
1561
+ if (!running && debateFinished === false && transcript.length > 1) { setStatus('Intervenci\u00f3n a\u00f1adida. Contin\u00faa el debate cuando quieras.'); }
1562
+ }
1563
+ $('interject-btn').addEventListener('click', interject);
1564
+ $('interject-txt').addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); interject(); } });
1565
+ $('devil-btn').addEventListener('click', runDevil);
1566
+ $('devil-btn2').addEventListener('click', runDevil);
1567
+ $('analyze-btn').addEventListener('click', () => runAnalysis(false));
1568
+
1569
+ /* ================= Ajustes ================= */
1570
+ const settingsModal = $('settings-modal');
1571
+ $('settings-btn').addEventListener('click', () => {
1572
+ $('set-repo').value = CONFIG.repo;
1573
+ $('set-file').value = CONFIG.file;
1574
+ $('set-ctx').value = CONFIG.nCtx;
1575
+ $('set-maxtokens').value = CONFIG.maxTokens;
1576
+ $('set-temp').value = CONFIG.temperature;
1577
+ $('set-rounds').value = CONFIG.rounds;
1578
+ $('set-economy').checked = CONFIG.economy;
1579
+ $('set-theme').checked = document.body.classList.contains('light');
1580
+ settingsModal.classList.add('open');
1581
+ });
1582
+ $('settings-cancel').addEventListener('click', () => settingsModal.classList.remove('open'));
1583
+ settingsModal.addEventListener('click', e => { if (e.target === settingsModal) settingsModal.classList.remove('open'); });
1584
+ $('set-model').addEventListener('change', () => {
1585
+ const [repo, file] = $('set-model').value.split('|');
1586
+ $('set-repo').value = repo; $('set-file').value = file;
1587
+ });
1588
+ $('apply-settings').addEventListener('click', async () => {
1589
+ const prof = PROFILES[$('set-profile').value];
1590
+ CONFIG.maxTokens = parseInt($('set-maxtokens').value) || prof.maxTokens;
1591
+ CONFIG.temperature = parseFloat($('set-temp').value) || prof.temperature;
1592
+ CONFIG.rounds = Math.min(6, Math.max(1, parseInt($('set-rounds').value) || prof.rounds));
1593
+ CONFIG.economy = $('set-economy').checked;
1594
+ document.body.classList.toggle('light', $('set-theme').checked);
1595
+ const newCtx = parseInt($('set-ctx').value) || prof.nCtx;
1596
+ const newRepo = $('set-repo').value.trim();
1597
+ const newFile = $('set-file').value.trim();
1598
+ if (CONFIG.economy) { CONFIG.maxTokens = Math.min(CONFIG.maxTokens, 160); }
1599
+ const reload = newCtx !== CONFIG.nCtx || newRepo !== CONFIG.repo || newFile !== CONFIG.file;
1600
+ CONFIG.nCtx = newCtx; CONFIG.repo = newRepo; CONFIG.file = newFile;
1601
+ settingsModal.classList.remove('open');
1602
+ if (reload || !wllama) { transcript = []; chatEl.innerHTML = ''; await loadModel(CONFIG.repo, CONFIG.file); }
1603
+ else setStatus('Ajustes aplicados.');
1604
+ });
1605
+
1606
+ /* ================= Init ================= */
1607
+ renderRoster();
1608
+ renderPresets();
1609
+ renderTemplates();
1610
+ engineBadge();
1611
+ updateStorageStat();
1612
+ if (CONFIG.autoload) loadModel(CONFIG.repo, CONFIG.file);
1613
+ else setStatus('Modo manual: carga el modelo desde Ajustes (\u2699\uFE0F).');
1614
+ </script>
1615
+ </body>
1616
+ </html>