File size: 48,259 Bytes
6f6a7fd
 
 
 
 
f7b9686
6f6a7fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7b9686
6f6a7fd
 
 
 
 
 
 
15accab
 
6f6a7fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a585fa5
da500e7
15accab
6f6a7fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c68a4a8
6f6a7fd
 
 
 
 
 
 
 
 
 
 
 
 
 
15accab
 
6f6a7fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b55117b
6f6a7fd
15accab
 
 
 
 
 
 
6f6a7fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c68a4a8
6f6a7fd
 
 
 
2f8a2e5
6f6a7fd
 
 
 
 
 
 
 
 
b55117b
a585fa5
b55117b
 
 
 
 
6f6a7fd
a585fa5
6f6a7fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53ed033
6f6a7fd
 
53ed033
6f6a7fd
 
 
 
53ed033
 
 
6f6a7fd
53ed033
 
6f6a7fd
 
 
 
 
53ed033
 
 
 
 
 
 
 
6f6a7fd
 
 
bef0e95
 
6f6a7fd
 
 
 
 
 
53ed033
6f6a7fd
 
 
 
 
 
 
 
15accab
 
6f6a7fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c68a4a8
a307c69
 
 
 
 
6f6a7fd
 
a307c69
6f6a7fd
 
e54db90
 
 
15accab
 
 
 
 
 
 
 
a307c69
 
6f6a7fd
 
 
 
 
 
 
 
 
 
a307c69
6f6a7fd
 
 
 
 
 
 
 
 
b55117b
6f6a7fd
 
15accab
6f6a7fd
a307c69
6f6a7fd
15accab
6f6a7fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b55117b
6f6a7fd
 
 
 
 
 
 
 
 
 
 
 
 
b55117b
 
6f6a7fd
 
b55117b
6f6a7fd
 
 
 
 
 
 
 
 
 
b55117b
6f6a7fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2010c30
 
 
 
 
 
 
 
 
 
6f6a7fd
 
 
 
2010c30
6f6a7fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2f28f3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Harbour &amp; FWH Studio</title>
<style>
:root{
  --bg:#0b141a; --surface:#111b21; --surface2:#202c33; --border:#2a3942;
  --text:#e9edef; --muted:#8696a0; --accent:#00a884;
  --header:#202c33; --header-text:#e9edef; --header-sub:#8696a0;
  --bubble-in:#202c33; --bubble-out:#005c4b; --sys:#2a3942; --sys-text:#ffd279;
  --input:#2a3942; --track:rgba(255,255,255,.12); --disabled:#374248;
}
body.light{
  --bg:#efeae2; --surface:#ffffff; --surface2:#f0f2f5; --border:#d1d7db;
  --text:#111b21; --muted:#667781;
  --header:#008069; --header-text:#ffffff; --header-sub:rgba(255,255,255,.75);
  --bubble-in:#ffffff; --bubble-out:#d9fdd3; --sys:#fdf3c6; --sys-text:#54656f;
  --input:#ffffff; --track:rgba(11,20,26,.08); --disabled:#aebac1;
}
*{box-sizing:border-box}
html,body{margin:0;padding:0;background:var(--bg);color:var(--text);
  font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;font-size:15px}
#app{max-width:1200px;margin:0 auto;display:flex;height:100vh;height:100dvh;
  box-shadow:0 0 14px rgba(0,0,0,.4);background:var(--bg)}

/* --- Lista de contactos (agentes) --- */
#sidebar{width:300px;flex:none;display:flex;flex-direction:column;min-height:0;
  background:var(--surface);border-right:1px solid var(--border)}
.side-header{display:flex;align-items:center;gap:10px;padding:10px 16px;
  background:var(--header);color:var(--header-text)}
.side-logo{width:38px;height:38px;border-radius:50%;flex:none;font-size:19px;
  background:linear-gradient(135deg,#00c49a,#025c4b);display:flex;align-items:center;justify-content:center;
  box-shadow:0 0 10px rgba(0,168,132,.45)}
.side-title{font-weight:600;font-size:16px;letter-spacing:.1px}
.side-count{font-weight:400;color:var(--muted);font-size:12.5px;margin-left:4px}
#contacts{flex:1;overflow-y:auto;padding:6px 0}
.contact{display:flex;align-items:center;gap:12px;padding:9px 14px;transition:background .15s}
.contact:hover{background:var(--surface2)}
.contact.active{background:var(--surface2)}
.c-avatar{width:46px;height:46px;border-radius:50%;display:flex;align-items:center;justify-content:center;
  font-size:22px;color:#fff;flex:none}
.c-info{flex:1;min-width:0;display:flex;flex-direction:column}
.c-name{font-size:15px;font-weight:600;color:var(--text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.c-role{font-size:12.5px;color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.contact.active .c-role{color:var(--accent);font-style:italic}
.c-dot{width:9px;height:9px;border-radius:50%;background:var(--accent);flex:none;box-shadow:0 0 6px var(--accent)}

/* --- Columna principal --- */
#main{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column}

header{display:flex;align-items:center;gap:10px;padding:8px 16px;background:var(--header);color:var(--header-text);
  border-bottom:none;box-shadow:0 1px 3px rgba(0,0,0,.3);z-index:2}
header .logo{width:40px;height:40px;border-radius:50%;background:linear-gradient(135deg,#00c49a,#025c4b);
  display:flex;align-items:center;justify-content:center;font-size:19px;color:#fff;flex:none;
  box-shadow:0 0 10px rgba(0,168,132,.45)}
header .title{font-weight:600;font-size:16px;letter-spacing:.1px;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
header .subtitle{font-size:12px;color:var(--header-sub);font-weight:400}
#settings-btn{background:none;border:none;color:var(--header-text);border-radius:50%;
  width:38px;height:38px;cursor:pointer;font-size:18px;display:flex;align-items:center;justify-content:center;transition:.15s}
#settings-btn:hover{background:rgba(255,255,255,.12)}

#chat{flex:1;overflow-y:auto;padding:20px 8%;display:flex;flex-direction:column;gap:8px;
  background-color:var(--bg);
  background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='120' viewBox='0 0 120 120'%3E%3Cg fill='none' stroke='%232a3942' stroke-width='1.4' opacity='0.55'%3E%3Ccircle cx='20' cy='20' r='6'/%3E%3Cpath d='M50 15h16a6 6 0 0 1 6 6v8a6 6 0 0 1-6 6h-9l-5 5v-5h-2a6 6 0 0 1-6-6v-8a6 6 0 0 1 6-6z'/%3E%3Cpath d='M15 60l4 4 8-8'/%3E%3Ccircle cx='95' cy='70' r='8'/%3E%3Cpath d='M40 95c4-6 12-6 16 0'/%3E%3Cpath d='M85 25l2.5 5 5 2.5-5 2.5-2.5 5-2.5-5-5-2.5 5-2.5z'/%3E%3Crect x='60' y='55' width='12' height='12' rx='3'/%3E%3Cpath d='M20 100q6-8 12 0'/%3E%3C/g%3E%3C/svg%3E")}
body.light #chat{
  background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='120' viewBox='0 0 120 120'%3E%3Cg fill='none' stroke='%23d8d1c6' stroke-width='1.4' opacity='0.5'%3E%3Ccircle cx='20' cy='20' r='6'/%3E%3Cpath d='M50 15h16a6 6 0 0 1 6 6v8a6 6 0 0 1-6 6h-9l-5 5v-5h-2a6 6 0 0 1-6-6v-8a6 6 0 0 1 6-6z'/%3E%3Cpath d='M15 60l4 4 8-8'/%3E%3Ccircle cx='95' cy='70' r='8'/%3E%3Cpath d='M40 95c4-6 12-6 16 0'/%3E%3Cpath d='M85 25l2.5 5 5 2.5-5 2.5-2.5 5-2.5-5-5-2.5 5-2.5z'/%3E%3Crect x='60' y='55' width='12' height='12' rx='3'/%3E%3Cpath d='M20 100q6-8 12 0'/%3E%3C/g%3E%3C/svg%3E")}
#chat::-webkit-scrollbar,#contacts::-webkit-scrollbar{width:6px;height:6px}
#chat::-webkit-scrollbar-thumb,#contacts::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px}
.msg{display:flex;gap:8px;animation:fadein .2s ease;max-width:100%}
.msg .avatar{width:36px;height:36px;border-radius:50%;display:flex;align-items:center;justify-content:center;
  font-size:17px;color:#fff;flex:none;margin-top:0}
.msg .content{flex:1;min-width:0;max-width:75%;background:var(--bubble-in);border-radius:8px;padding:6px 9px 8px;
  box-shadow:0 1px 1px rgba(0,0,0,.3)}
.msg .who{font-size:13px;font-weight:600;margin-bottom:2px}
.msg .who .round{font-weight:400;color:var(--muted);margin-left:6px;font-size:11px}
.msg .body{line-height:1.42;word-wrap:break-word;color:var(--text);font-size:14.5px}
.msg .body p{margin:.35em 0}
.msg.user{justify-content:flex-end}
.msg.user .content{flex:none;background:var(--bubble-out);border:none;
  border-radius:8px;padding:7px 10px}
.msg.user .who{display:none}
.msg.err{align-self:center;max-width:92%;background:var(--sys);color:var(--sys-text);font-size:12.5px;
  border-radius:8px;padding:6px 12px;text-align:center;box-shadow:0 1px 1px rgba(0,0,0,.3)}
@keyframes fadein{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}
@keyframes pulse{0%,100%{opacity:.3}50%{opacity:1}}
.msg.streaming .body::after{content:"";display:inline-block;width:7px;height:7px;border-radius:50%;
  background:var(--accent);margin-left:5px;animation:pulse 1s infinite}
details.think{margin:2px 0 6px;font-size:12.5px;color:var(--muted)}
details.think summary{cursor:pointer;font-size:12px;font-style:italic}
details.think .t{white-space:pre-wrap;border-left:3px solid var(--border);padding-left:10px;margin-top:5px;font-size:12.5px}

#controls{padding:8px 12px;background:var(--surface);display:flex;gap:8px;align-items:center;border-top:none}
#topic-sugg{flex:none;max-width:170px;background:var(--input);color:var(--muted);border:none;
  border-radius:8px;padding:11px 8px;font-size:13px;cursor:pointer;outline:none}
#topic{flex:1;min-width:0;background:var(--input);border:none;color:var(--text);
  border-radius:8px;padding:11px 14px;font-size:15px;outline:none}
#topic::placeholder{color:var(--muted)}
#start-btn{flex:none;background:var(--accent);color:#fff;border:none;border-radius:999px;padding:11px 18px;
  cursor:pointer;font-weight:600;font-size:14px;transition:background .15s;white-space:nowrap;box-shadow:0 1px 2px rgba(0,0,0,.3)}
#start-btn:hover{background:#02b08a}
#start-btn:disabled{background:var(--disabled);color:var(--muted);cursor:default;box-shadow:none}
#stop-btn{flex:none;background:transparent;border:1px solid #ea0038;color:#ea0038;border-radius:999px;
  padding:10px 16px;cursor:pointer;font-weight:600;font-size:14px;display:none}

#settings{display:none;margin:8px 12px 10px;padding:16px;border:1px solid var(--border);
  border-radius:12px;background:var(--surface);box-shadow:0 2px 6px rgba(0,0,0,.3)}
#settings.open{display:block}
#settings label{display:block;font-size:12px;color:var(--muted);margin:10px 0 4px}
#settings input,#settings textarea,#settings select{width:100%;background:var(--input);color:var(--text);
  border:1px solid var(--border);border-radius:8px;padding:9px 12px;font-size:14px;font-family:inherit;outline:none}
#settings input:focus,#settings textarea:focus,#settings select:focus{border-color:var(--accent)}
#settings textarea{min-height:150px;font-family:ui-monospace,"SF Mono",Menlo,monospace;font-size:12px}
#settings .row{display:flex;gap:10px;flex-wrap:wrap}
#settings .row>div{flex:1;min-width:120px}
#apply-settings{margin-top:12px;background:var(--accent);border:none;color:#fff;border-radius:999px;
  padding:10px 18px;cursor:pointer;font-weight:600}

#status{padding:6px 16px;font-size:12px;color:var(--muted);background:var(--bg)}
#progress{height:3px;background:var(--track)}
#progress>div{height:100%;width:0;background:var(--accent);transition:width .25s}
footer{padding:10px 16px;font-size:11px;color:var(--muted);border-top:1px solid var(--border);background:var(--surface);
  display:flex;gap:8px 16px;flex-wrap:wrap;justify-content:center;text-align:center}
footer a{color:var(--accent);text-decoration:none}


/* --- Editor interactivo de agente --- */
.contact{cursor:pointer}
#agent-modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.55);z-index:10;
  align-items:center;justify-content:center;padding:16px}
#agent-modal.open{display:flex}
#agent-modal .card{width:100%;max-width:420px;max-height:90vh;overflow-y:auto;background:var(--surface);
  border:1px solid var(--border);border-radius:12px;padding:16px;box-shadow:0 8px 24px rgba(0,0,0,.4)}
#agent-modal h3{margin:0 0 4px;font-size:16px;color:var(--text)}
#agent-modal .hint{font-size:12px;color:var(--muted);margin-bottom:4px}
#agent-modal label{display:block;font-size:12px;color:var(--muted);margin:10px 0 4px}
#agent-modal input,#agent-modal textarea{width:100%;background:var(--input);color:var(--text);
  border:1px solid var(--border);border-radius:8px;padding:9px 12px;font-size:14px;font-family:inherit;outline:none}
#agent-modal input:focus,#agent-modal textarea:focus{border-color:var(--accent)}
#agent-modal textarea{min-height:110px;resize:vertical}
#agent-modal .row{display:flex;gap:10px}
#agent-modal .row>div{flex:1;min-width:0}
#agent-emoji{text-align:center}
#agent-color{padding:4px;height:41px;cursor:pointer}
#agent-modal .btns{display:flex;gap:10px;margin-top:14px;justify-content:flex-end}
#agent-save{background:var(--accent);border:none;color:#fff;border-radius:999px;padding:10px 18px;cursor:pointer;font-weight:600}
#agent-cancel{background:transparent;border:1px solid var(--border);color:var(--muted);border-radius:999px;
  padding:10px 18px;cursor:pointer;font-weight:600}


.add-av{background:transparent !important;border:2px dashed var(--border);color:var(--muted);
  font-size:22px;font-weight:400;box-shadow:none !important}
.add-contact:hover .add-av{border-color:var(--accent);color:var(--accent)}
.add-contact:hover .c-name{color:var(--accent)}
#agent-delete{background:transparent;border:1px solid #ea0038;color:#ea0038;border-radius:999px;
  padding:10px 18px;cursor:pointer;font-weight:600;margin-right:auto}


/* --- Historial de temas --- */
#history{flex:none;max-height:34%;display:flex;flex-direction:column;border-top:1px solid var(--border)}
.hist-header{display:flex;align-items:center;justify-content:space-between;padding:8px 16px 4px;
  font-size:12.5px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.4px}
#hist-clear{background:none;border:none;color:var(--muted);cursor:pointer;font-size:14px;padding:2px 4px;border-radius:6px}
#hist-clear:hover{color:var(--text);background:var(--surface2)}
#hist-list{overflow-y:auto;padding:0 8px 8px}
.hist-item{padding:7px 10px;border-radius:8px;cursor:pointer}
.hist-item:hover{background:var(--surface2)}
.hist-topic{font-size:13.5px;color:var(--text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.hist-meta{font-size:11.5px;color:var(--muted);margin-top:1px}
.hist-empty{font-size:12px;color:var(--muted);font-style:italic;padding:6px 10px}

@media (max-width:760px){
  #app{flex-direction:column;max-width:none}
  #sidebar{width:100%;flex:none;border-right:none;border-bottom:1px solid var(--border)}
  .side-header{display:none}
  #contacts{display:flex;overflow-x:auto;padding:8px 10px;gap:6px}
  .contact{flex:none;flex-direction:column;gap:4px;padding:6px 10px;min-width:64px;justify-content:center}
  .contact .c-info{align-items:center;text-align:center}
  .c-role{display:none}
  .c-dot{display:none}
  .c-avatar{width:44px;height:44px;font-size:21px}
  #chat{padding:12px 4%;gap:7px}
  #controls{padding:8px 8px}
  header{padding:8px 10px}
  header .subtitle{display:none}
  .msg .avatar{width:32px;height:32px;font-size:16px}
  .msg .content{max-width:85%}
  #settings{margin:0 8px 8px}
  #history{display:none}
  #topic-sugg{max-width:110px}
}
</style>
</head>
<body>
<div id="app">
  <aside id="sidebar">
    <div class="side-header">
      <span class="side-logo">&#129302;</span>
      <span class="side-title">Agentes<span class="side-count" id="side-count">(3)</span></span>
    </div>
    <div id="contacts"></div>
    <div id="history">
      <div class="hist-header"><span>Temas debatidos</span><button id="hist-clear" title="Borrar historial">&#128465;</button></div>
      <div id="hist-list"></div>
    </div>
  </aside>
  <div id="main">
    <header>
      <span class="logo">&#129302;</span>
      <span class="title" id="title">Harbour &amp; FWH Studio <span class="subtitle" id="subtitle"></span></span>
      <button id="settings-btn" title="Ajustes">&#9881;</button>
    </header>

    <div id="settings">
      <div class="row">
        <div><label>Modelo predefinido</label><select id="set-preset">
          <option value="">(personalizado)</option>
          <option value="bartowski/MiMo-V2.6-Distill-Qwen-9B-GGUF|MiMo-V2.6-Distill-Qwen-9B-Q4_K_M.gguf" selected>MiMo-V2.6 9B Q4_K_M (~5,8 GB; requiere bastante almacenamiento libre en el navegador)</option>
          <option value="bartowski/MiMo-V2.6-Distill-Qwen-9B-GGUF|MiMo-V2.6-Distill-Qwen-9B-Q3_K_M.gguf">MiMo-V2.6 9B Q3_K_M (~4,4 GB; menos calidad, menos cuota)</option>
        </select></div>
      </div>
      <div class="row">
        <div><label>Repositorio Hugging Face</label><input id="set-repo"></div>
        <div><label>Archivo GGUF</label><input id="set-file"></div>
      </div>
      <div class="row">
        <div><label>Contexto (tokens)</label><input id="set-ctx" type="number" step="512" min="2048"></div>
        <div><label>M&aacute;x. tokens por turno</label><input id="set-maxtokens" type="number" step="32" min="64"></div>
        <div><label>Temperatura</label><input id="set-temp" type="number" step="0.05" min="0" max="2"></div>
        <div><label>Rondas</label><input id="set-rounds" type="number" step="1" min="1" max="20"></div>
        <div><label>Orden de turnos</label><select id="set-order"><option value="seq">Secuencial</option><option value="rand">Aleatorio por ronda</option></select></div>
      </div>
      <label>Agentes (JSON: name, emoji, color, system)</label>
      <textarea id="set-agents" spellcheck="false"></textarea>
      <button id="apply-settings">Aplicar</button>
    </div>

    <div id="chat"></div>

    <div id="controls">
      <select id="topic-sugg" title="Temas sugeridos"></select>
      <input id="topic" placeholder="Pregunta sobre Harbour o FiveWin y los expertos responden&hellip;">
      <button id="start-btn" disabled>Cargando modelo&hellip;</button>
      <button id="stop-btn">Detener</button>
    </div>

    <div id="status">Iniciando&hellip;</div>
    <div id="progress"><div></div></div>
    <footer>
      <span>La conversación se procesa en tu navegador (WASM/CPU; la generación tarda unos minutos por intervención). Solo se conecta a Hugging Face para descargar el modelo (5,84 GB con MiMo Q4_K_M; queda en la caché del navegador) y a jsDelivr para las librerías.</span>
      <span>Contexto experto: extractos de la documentación pública de <a href="https://fivetechsoft.github.io/FWH_docs/en/getting-started/overview.html" target="_blank" rel="noopener">FWH</a> (434 páginas, fragmentos de ~1.600 caracteres), documentación de <a href="https://github.com/harbour/core" target="_blank" rel="noopener">harbour/core</a> e hilos públicos de los <a href="https://forums.fivetechsupport.com" target="_blank" rel="noopener">foros FiveTech</a>, incluidos en este Space. El modelo puede proponer código incorrecto: valídalo siempre compilando.</span>
      <span>Motor: <a href="https://github.com/ngxson/wllama" target="_blank" rel="noopener">wllama</a> (MIT) &middot; inspirado en <a href="https://huggingface.co/spaces/fivetech/Multi-Agent-Debate-MiMo-WebGPU" target="_blank" rel="noopener">Multi-Agent Debate</a> &middot; modelo: <a href="https://huggingface.co/bartowski/MiMo-V2.6-Distill-Qwen-9B-GGUF" target="_blank" rel="noopener">MiMo-V2.6-9B</a> (Q4_K_M por defecto, ~5,8 GB; Q3 en Ajustes). Su descarga es grande y puede no caber en la cuota de almacenamiento del navegador</span>
    </footer>
  </div>
</div>


<div id="agent-modal">
  <div class="card">
    <h3 id="agent-modal-title">Editar agente</h3>
    <div class="hint">Cambia su nombre y sus cualidades; se aplica al instante en esta sesión, igual que los Ajustes.</div>
    <div class="row">
      <div style="flex:2"><label>Nombre</label><input id="agent-name"></div>
      <div><label>Avatar (emoji)</label><input id="agent-emoji" maxlength="4"></div>
      <div><label>Color</label><input id="agent-color" type="color"></div>
    </div>
    <label>Cualidades (personalidad e instrucciones)</label>
    <textarea id="agent-system" spellcheck="false" placeholder="Ej.: Eres Dora, la optimista del grupo. Ves oportunidades en cada idea y animas al grupo a probar."></textarea>
    <div class="btns">
      <button id="agent-delete">Eliminar</button>
      <button id="agent-cancel">Cancelar</button>
      <button id="agent-save">Guardar</button>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script type="module">
import { Wllama } from 'https://cdn.jsdelivr.net/npm/@wllama/wllama@3.8.1/esm/index.js';

const params = new URLSearchParams(location.search);

const DEFAULT_AGENTS = [
  { name: 'Harbour', emoji: '\u{2693}', color: '#58a6ff',
    system: 'Eres Harbour, experto en el lenguaje Harbour (sucesor libre de Clipper/xBase): compilador, hbmk2, RDDs, arrays, codeblocks, clases, multihilo y compatibilidad con xHarbour. Basas tus respuestas en la documentaci\u00f3n p\u00fablica de harbour/core incluida en tu contexto; la citas brevemente cuando la usas y admites con naturalidad cuando algo no consta.' },
  { name: 'FiveWin', emoji: '\u{1FA9F}', color: '#bf5af2',
    system: 'Eres FiveWin, experta en FiveWin for Harbour (FWH), la librer\u00eda GUI comercial de FiveTech para Windows: clases TWindow, TDialog, TXBrowse, TGet, men\u00fas, impresi\u00f3n y builds 32/64 bits. Te apoyas en el conocimiento p\u00fablico de los foros de FiveTech incluido en tu contexto; citas el hilo cuando lo usas y admites cuando algo no consta.' },
  { name: 'Mentor', emoji: '\u{1F3AF}', color: '#3fb950',
    system: 'Eres Mentor, el integrador del grupo. Sintetizas lo aportado por Harbour y FiveWin, propones ejemplos de c\u00f3digo concretos cuando ayudan y se\u00f1alas el siguiente paso o prueba a realizar. Cierras cada ronda con una conclusi\u00f3n breve.' },
];

const CONFIG = {
  modelUrl: params.get('modelUrl') || '',
  repo: params.get('repo') || 'bartowski/MiMo-V2.6-Distill-Qwen-9B-GGUF',
  file: params.get('file') || 'MiMo-V2.6-Distill-Qwen-9B-Q4_K_M.gguf',
  nCtx: parseInt(params.get('ctx')) || 8192,
  maxTokens: parseInt(params.get('maxTokens')) || 512,
  temperature: parseFloat(params.get('temp')) || 0.7,
  rounds: parseInt(params.get('rounds')) || 2,
  autoload: params.get('autoload') !== 'false',
  order: params.get('order') === 'rand' ? 'rand' : 'seq',
};
if (params.get('theme') === 'light') document.body.classList.add('light');
const AGENTS_KEY = 'hfw_agents';
function loadStoredAgents() {
  try {
    const a = JSON.parse(localStorage.getItem(AGENTS_KEY));
    return (Array.isArray(a) && a.length >= 2 && a.every(x => x && x.name && x.system)) ? a : null;
  } catch (e) { return null; }
}
function persistAgents() {
  try { localStorage.setItem(AGENTS_KEY, JSON.stringify(agents)); } catch (e) {}
}
let agents = loadStoredAgents() || DEFAULT_AGENTS;
if (params.get('agents')) {
  try { agents = JSON.parse(params.get('agents')); } catch (e) { console.warn('agents JSON inv\u00e1lido', e); }
}

const chatEl = document.getElementById('chat');
const statusEl = document.getElementById('status');
const progressEl = document.getElementById('progress').firstElementChild;
const topicEl = document.getElementById('topic');
const startBtn = document.getElementById('start-btn');
const stopBtn = document.getElementById('stop-btn');
const contactsEl = document.getElementById('contacts');
const subtitleEl = document.getElementById('subtitle');

let wllama = null;
let running = false;
let genError = false;
let stopRequested = false;
let inflight = null;
function raceStop(p) {
  return new Promise((res, rej) => {
    const t = setInterval(() => { if (stopRequested) { clearInterval(t); res('__stop__'); } }, 250);
    p.then(r => { clearInterval(t); res(r); }, e => { clearInterval(t); rej(e); });
  });
}
let transcript = [];   // {name|null(user), text}
let topic = '';

function setStatus(t) { statusEl.textContent = t; }
function setProgress(p) { progressEl.style.width = Math.max(0, Math.min(100, p)) + '%'; }

function esc(s){ const d = document.createElement('div'); d.textContent = s; return d.innerHTML; }

// --- Avatares y lista de contactos ---
function shade(hex, amt) {
  const n = parseInt(String(hex).replace('#','').slice(0,6), 16);
  if (isNaN(n)) return hex;
  const f = v => Math.max(0, Math.min(255, v + amt));
  const r = f(n >> 16), g = f((n >> 8) & 255), b = f(n & 255);
  return '#' + ((r << 16) | (g << 8) | b).toString(16).padStart(6, '0');
}
function avatarBg(color) {
  return `linear-gradient(135deg, ${shade(color, 34)} 0%, ${color} 55%, ${shade(color, -38)} 100%)`;
}
function roleOf(agent) {
  const m = /Eres\s+[^,]+,\s*([^\.]+)\./i.exec(agent.system || '');
  let r = m ? m[1].trim() : 'Agente del debate';
  r = r.replace(/\s+del grupo\s*$/i, '').replace(/^(el|la|los|las)\s+/i, '');
  return r ? r.charAt(0).toUpperCase() + r.slice(1) : 'Agente del debate';
}
function renderContacts() {
  contactsEl.innerHTML = '';
  agents.forEach((a, i) => {
    const c = document.createElement('div');
    c.className = 'contact';
    c.dataset.name = a.name;
    c.title = 'Editar agente';
    c.addEventListener('click', () => openAgentEditor(i));
    const av = document.createElement('div');
    av.className = 'c-avatar';
    av.style.background = avatarBg(a.color);
    av.style.boxShadow = `0 0 12px ${a.color}66`;
    av.textContent = a.emoji;
    const info = document.createElement('div');
    info.className = 'c-info';
    const nm = document.createElement('div');
    nm.className = 'c-name'; nm.textContent = a.name;
    const rl = document.createElement('div');
    rl.className = 'c-role'; rl.textContent = roleOf(a);
    info.appendChild(nm); info.appendChild(rl);
    const dot = document.createElement('div');
    dot.className = 'c-dot';
    c.appendChild(av); c.appendChild(info); c.appendChild(dot);
    contactsEl.appendChild(c);
  });
  const add = document.createElement('div');
  add.className = 'contact add-contact';
  add.title = 'A\u00f1adir agente';
  add.innerHTML = '<div class="c-avatar add-av">+</div><div class="c-info">' +
    '<div class="c-name">A\u00f1adir agente</div><div class="c-role">Nuevo participante</div></div>';
  add.addEventListener('click', () => openAgentEditor(-1));
  contactsEl.appendChild(add);
  document.getElementById('side-count').textContent = `(${agents.length})`;
  subtitleEl.textContent = agents.map(a => a.name).join(', ') + ', T\u00fa';
}
function markActive(name) {
  contactsEl.querySelectorAll('.contact').forEach(c => {
    const on = c.dataset.name === name;
    c.classList.toggle('active', on);
    const rl = c.querySelector('.c-role');
    if (on) { if (!rl.dataset.orig) rl.dataset.orig = rl.textContent; rl.textContent = 'escribiendo\u2026'; }
    else if (rl.dataset.orig) { rl.textContent = rl.dataset.orig; delete rl.dataset.orig; }
  });
}

// --- Editor interactivo de agentes (editar, a\u00f1adir, quitar) ---
const agentModal = document.getElementById('agent-modal');
const deleteBtn = document.getElementById('agent-delete');
let editingAgent = -1;
function openAgentEditor(i) {
  editingAgent = i;
  const a = agents[i] || {};
  document.getElementById('agent-modal-title').textContent = i >= 0 ? 'Editar agente' : 'A\u00f1adir agente';
  deleteBtn.style.display = i >= 0 ? 'inline-block' : 'none';
  document.getElementById('agent-name').value = a.name || '';
  document.getElementById('agent-emoji').value = a.emoji || '\u{1F916}';
  document.getElementById('agent-color').value = /^#[0-9a-fA-F]{6}$/.test(a.color || '') ? a.color : '#bf5af2';
  document.getElementById('agent-system').value = a.system || '';
  agentModal.classList.add('open');
  document.getElementById('agent-name').focus();
}
document.getElementById('agent-cancel').addEventListener('click', () => agentModal.classList.remove('open'));
agentModal.addEventListener('click', e => { if (e.target === agentModal) agentModal.classList.remove('open'); });
deleteBtn.addEventListener('click', () => {
  const a = agents[editingAgent];
  if (!a) return;
  if (agents.length <= 2) { alert('Se necesitan al menos 2 agentes.'); return; }
  if (!confirm(`\u00bfEliminar a ${a.name} del debate?`)) return;
  agents.splice(editingAgent, 1);
  persistAgents();
  renderContacts();
  agentModal.classList.remove('open');
  setStatus(`Agente eliminado: ${a.name}. Quedan ${agents.length}.`);
});
document.getElementById('agent-save').addEventListener('click', () => {
  const name = document.getElementById('agent-name').value.trim();
  if (!name) { alert('El nombre no puede estar vac\u00edo.'); return; }
  const emoji = document.getElementById('agent-emoji').value.trim() || '\u{1F916}';
  const color = document.getElementById('agent-color').value;
  const system = document.getElementById('agent-system').value.trim();
  if (!system) { alert('Describe las cualidades del agente.'); return; }
  if (editingAgent >= 0) agents[editingAgent] = { name, emoji, color, system };
  else agents.push({ name, emoji, color, system });
  persistAgents();
  renderContacts();
  agentModal.classList.remove('open');
  setStatus(editingAgent >= 0 ? `Agente actualizado: ${name}.` : `Agente a\u00f1adido: ${name}. Ya son ${agents.length}.`);
});


// --- Historial de temas (localStorage) ---
const HIST_KEY = 'hfw_history';
const histListEl = document.getElementById('hist-list');
function loadHistory() {
  try { return JSON.parse(localStorage.getItem(HIST_KEY)) || []; } catch (e) { return []; }
}
function saveHistory(h) {
  try { localStorage.setItem(HIST_KEY, JSON.stringify(h.slice(0, 30))); } catch (e) {}
}
function renderHistory() {
  const h = loadHistory();
  histListEl.innerHTML = '';
  if (!h.length) {
    const e = document.createElement('div');
    e.className = 'hist-empty';
    e.textContent = 'Los temas que debatas se guardar\u00e1n aqu\u00ed, en este navegador.';
    histListEl.appendChild(e);
    return;
  }
  h.forEach(item => {
    const d = document.createElement('div');
    d.className = 'hist-item';
    d.title = 'Reutilizar este tema';
    const t = document.createElement('div');
    t.className = 'hist-topic'; t.textContent = item.topic;
    const m = document.createElement('div');
    m.className = 'hist-meta';
    m.textContent = new Date(item.ts).toLocaleString('es-ES', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' }) +
      ' \u00b7 ' + item.agents + ' agentes';
    d.appendChild(t); d.appendChild(m);
    d.addEventListener('click', () => { topicEl.value = item.topic; topicEl.focus(); });
    histListEl.appendChild(d);
  });
}
function recordTopic(topicText) {
  const h = loadHistory();
  if (h[0] && h[0].topic === topicText) return;
  h.unshift({ topic: topicText, ts: Date.now(), agents: agents.length });
  saveHistory(h);
  renderHistory();
}
document.getElementById('hist-clear').addEventListener('click', () => {
  if (!loadHistory().length) return;
  if (!confirm('\u00bfBorrar el historial de temas?')) return;
  saveHistory([]);
  renderHistory();
});

renderContacts();
renderHistory();

function addMsg(agent, isUser = false) {
  const d = document.createElement('div');
  d.className = 'msg' + (isUser ? ' user' : '');
  const content = document.createElement('div');
  content.className = 'content';
  const who = document.createElement('div');
  who.className = 'who';
  const body = document.createElement('div');
  body.className = 'body';
  if (isUser) { who.textContent = 'T\u00fa'; }
  else {
    const av = document.createElement('div');
    av.className = 'avatar';
    av.style.background = avatarBg(agent.color);
    av.style.boxShadow = '0 0 8px ' + agent.color + '55';
    av.textContent = agent.emoji;
    d.appendChild(av);
    who.textContent = agent.name;
    who.style.color = agent.color;
  }
  content.appendChild(who); content.appendChild(body);
  d.appendChild(content);
  chatEl.appendChild(d);
  chatEl.scrollTop = chatEl.scrollHeight;
  return { el: d, body, content };
}

function addErr(text) {
  const d = document.createElement('div');
  d.className = 'msg err';
  d.textContent = text;
  chatEl.appendChild(d);
}

async function loadModel(repo, file) {
  const url = CONFIG.modelUrl || `https://huggingface.co/${repo}/resolve/main/${file}`;
  startBtn.disabled = true;
  setProgress(0);
  setStatus(`Descargando ${file} (ctx ${CONFIG.nCtx})\u2026`);
  try {
    if (wllama) await wllama.exit();
    wllama = new Wllama({
      'default': 'https://cdn.jsdelivr.net/npm/@wllama/wllama@3.8.1/esm/wasm/wllama.wasm',
    }, { parallelDownloads: 5 });
    await wllama.loadModelFromUrl(url, {
      n_gpu_layers: 999,
      n_ctx: CONFIG.nCtx,
      n_batch: parseInt(params.get('batch')) || 512,
      n_threads: Math.max(1, Math.min(8, navigator.hardwareConcurrency || 4)),
      progressCallback: ({ loaded, total }) => {
        if (total > 0) {
          const pct = Math.round((loaded / total) * 100);
          setProgress(pct);
          setStatus(`Descargando\u2026 ${pct}% (${(loaded / 1048576).toFixed(0)} MB)`);
        }
      },
    });
    // Canario: una generación mínima confirma que el modelo puede generar, no solo cargar.
    setStatus('Comprobando generaci\u00f3n b\u00e1sica\u2026');
    try {
      await wllama.createCompletion({ prompt: '<|im_start|>user\nhola<|im_end|>\n<|im_start|>assistant\n', max_tokens: 2, temperature: 0 });
    } catch (e2) {
      throw new Error('El modelo carg\u00f3 pero NO puede generar en este navegador/motor: ' + (e2?.message || e2));
    }
    setProgress(100);
    setStatus(`Modelo cargado; comprobaci\u00f3n breve de generaci\u00f3n superada. ${agents.length} agentes: ${agents.map(a => a.name).join(', ')}.`);
    startBtn.disabled = false;
    startBtn.textContent = 'Iniciar debate';
    topicEl.focus();
  } catch (e) {
    console.error(e);
    setStatus('Error al cargar el modelo');
    addErr('No se pudo cargar el modelo: ' + (e?.message || e));
    const retry = document.createElement('button');
    retry.textContent = 'Limpiar cach\u00e9 y reintentar';
    retry.style.cssText = 'margin-top:6px;background:var(--accent);border:none;color:#fff;border-radius:999px;padding:8px 14px;cursor:pointer;font-weight:700';
    retry.addEventListener('click', async () => {
      retry.disabled = true; retry.textContent = 'Limpiando\u2026';
      try {
        if ('caches' in window) for (const k of await caches.keys()) await caches.delete(k);
        if (indexedDB.databases) for (const db of await indexedDB.databases())
          await new Promise(r => { const q = indexedDB.deleteDatabase(db.name); q.onsuccess = q.onerror = q.onblocked = r; });
        if (navigator.storage?.estimate) {
          const dir = await navigator.storage.getDirectory().catch(() => null);
          if (dir) for await (const k of dir.keys()) await dir.removeEntry(k, { recursive: true }).catch(() => {});
        }
      } catch (_) {}
      loadModel(repo, file);
    });
    const errBox = chatEl.lastElementChild;
    if (errBox) { errBox.appendChild(document.createElement('br')); errBox.appendChild(retry); }
  }
}


// --- Base de conocimiento (fuentes públicas) ---
let KB = [];
fetch('knowledge.json').then(r => r.ok ? r.json() : []).then(k => {
  KB = k;
  KB.forEach(e => { e._t = tok(e.title); e._x = tok(e.title + ' ' + e.text); e._ts = ' ' + e._t.join(' ') + ' '; e._xs = ' ' + e._x.join(' ') + ' '; });
  console.log('KB entradas:', KB.length);
}).catch(() => {});
const KB_STOP = new Set(('de la el en los del se las por un una para con no su al lo como mas o pero sus le ya este esta entre cuando muy sin sobre tambien hasta hay donde quien desde todo nos durante uno les ni contra otros ese eso ante ellos esto antes algunos que unos yo otro otras otra tanto esa estos mucho quienes nada muchos cual sea poco ella estar haber estas the is are was were for with that this from have has not but what all can you your their they them his her its our who how when where which will would there been more other into could than then some any each most over such only also and use used using get set com para como una con por que los las del fivewin fwh harbour aplicacion app usar cliente clientes client ver hacer').split(/\s+/));
function tok(s) {
  s = (s || '').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '');
  return s.split(/[^a-z0-9_$]+/).filter(w => w.length >= 3 && !KB_STOP.has(w));
}
const KB_EXP = { dialogo:['dialog'], dialogos:['dialog'], ventana:['window'], ventanas:['window'], cadena:['string'], tabla:['table','dbf'], tablas:['table','dbf'], indice:['index'], indices:['index'], campo:['field'], campos:['field'], boton:['button'], botones:['button'], informe:['report'], informes:['report'], impresora:['printer'], imprimir:['print'], migrar:['migrate'], migracion:['migration'], conectar:['connect'], conexion:['connection'], datos:['data'], codigo:['code'], archivo:['file'], fichero:['file'], carpeta:['folder'], buscar:['search'], correo:['mail','smtp'], navegador:['webview','browser'], compilador:['compiler'], compilar:['build','compile'], libreria:['library'], funcion:['function'], funciones:['function'], clase:['class'], clases:['class'], metodo:['method'], metodos:['method'], propiedad:['property'], propiedades:['property'], evento:['event'], eventos:['event'], pestana:['tab'], cinta:['ribbon'], calendario:['calendar'], grafico:['graph'], imagen:['image'], usuario:['user'], contrasena:['password'], factura:['invoice'], pedido:['order'], cliente:['client'], clientes:['client'], proveedor:['supplier'], listado:['list'], cuadro:['box'], crear:['create'], creo:['create'], ejemplo:['example'], ejemplos:['example'], error:['error'], errores:['error'], barras:['barcode'] };
function kbNgrams(w, n = 6) { if (w.length <= n) return [w]; const g = []; for (let i = 0; i + n <= w.length; i++) g.push(w.slice(i, i + n)); return g; }
function kbRetrieve(query, agentName, maxChars = 3000, k = 5) {
  if (!KB.length) return '';
  const qt = new Set();
  for (const w of tok(query)) { qt.add(w); (KB_EXP[w] || []).forEach(x => qt.add(x)); }
  if (!qt.size) return '';
  const scored = [];
  for (const e of KB) {
    let sc = 0;
    for (const w of qt) {
      if (e._t.includes(w)) { sc += 3; continue; }
      if (w.length >= 3 && e._t.some(t => (t.length >= 4 && (t.includes(w) || w.includes(t))))) { sc += 2; continue; }
      if (e._x.includes(w)) { sc += 1; continue; }
      if (w.length >= 6) {
        const gs = kbNgrams(w);
        if (gs.some(g => e._ts.includes(g))) { sc += 2; continue; }
        if (gs.some(g => e._xs.includes(g))) { sc += 0.5; }
      }
    }
    if (/^Harbour/i.test(agentName) && e.src.indexOf('harbour/core') === 0) sc *= 1.7;
    if (/^FiveWin/i.test(agentName) && e.src.indexOf('Foro') === 0) sc *= 1.7;
    if (/^FiveWin/i.test(agentName) && e.src.indexOf('FWH docs') === 0) sc *= 1.7;
    if (/^Mentor/i.test(agentName) && e.src.indexOf('FWH docs') === 0) sc *= 1.2;
    if (sc > 0) scored.push([sc, e]);
  }
  scored.sort((a, b) => b[0] - a[0]);
  let out = '', n = 0;
  for (const [sc, e] of scored) {
    if (n >= k || out.length + e.text.length > maxChars) break;
    out += `\n[${e.title} \u2014 ${e.src}]\n${e.text.slice(0, 1000)}\n`;
    n++;
  }
  return out.trim();
}

const RULES = 'Est\u00e1s en una conversaci\u00f3n entre varios agentes. ' +
  'Responde SOLO con tu intervenci\u00f3n: 2-5 frases, directas, en el idioma de la conversaci\u00f3n. ' +
  'No repitas lo ya dicho; reacciona a la \u00faltima intervenci\u00f3n. ' +
  'No escribas tu nombre ni ning\u00fan prefijo como "Nombre:". No uses listas largas. ' +
  'No inventes nombres de clases, m\u00e9todos, funciones ni versiones: si no est\u00e1 en el contexto o no lo sabes, dilo expresamente. Si usas el contexto, cita la fuente entre corchetes con su t\u00edtulo exacto.';

function transcriptText(maxChars = 9000) {
  const lines = transcript.map(m => `${m.name || 'Usuario'}: ${m.text}`);
  let out = lines.join('\n\n');
  while (out.length > maxChars && lines.length > 2) {
    lines.splice(1, 1); // conserva el tema (primera l\u00ednea) y lo m\u00e1s reciente
    out = lines.join('\n\n');
  }
  return out;
}

async function agentTurn(agent) {
  const view = transcriptText();
  const kb = kbRetrieve(topic + '\n' + view.slice(-900), agent.name);
  const messages = [
    { role: 'system', content: agent.system + ' ' + RULES +
      (kb ? '\n\nContexto de referencia (fuentes p\u00fablicas; \u00fasalo solo si es pertinente y c\u00edtalo brevemente):\n' + kb : '') },
    { role: 'user', content:
      `Tema del debate: ${topic}\n\n` +
      (view ? `Conversaci\u00f3n hasta ahora:\n${view}\n\n` : 'A\u00fan no hay intervenciones.\n\n') +
      `Ahora hablas t\u00fa, ${agent.name}. Escribe tu intervenci\u00f3n.` },
  ];
  const { el, body } = addMsg(agent);
  el.classList.add('streaming');
  markActive(agent.name);
  let think = null;
  let answer = '', reasoning = '', count = 0;
  setStatus(`${agent.name} est\u00e1 escribiendo\u2026`);
  try {
    // wllama antiguo no aceptaba la plantilla de chat embebida en este GGUF (assert
    // chat_templates en oaicompat_chat_params_parse), y el override chat_template
    // de LoadModelParams no se aplica. Usamos completion cruda con ChatML manual.
    const prompt = messages.map(m => `<|im_start|>${m.role}\n${m.content}<|im_end|>\n`).join('') + '<|im_start|>assistant\n';
    const streamP = wllama.createCompletion({
      prompt,
      max_tokens: CONFIG.maxTokens,
      temperature: CONFIG.temperature,
      stop: ['<|im_end|>', '<|im_start|>'],
      stream: true,
    });
    streamP.catch(() => {});
    const stream = await raceStop(streamP);
    if (stream === '__stop__') { streamP.then(st => { inflight = st; const s0 = st; (async () => { try { for await (const _ of st) {} } catch (_) {} if (inflight === s0) inflight = null; })(); }).catch(() => {}); el.remove(); markActive(null); setStatus('Detenido'); return; }
    inflight = stream;
    let pending = null;
    while (true) {
      pending = stream.next();
      pending.catch(() => {});
      const step = await raceStop(pending);
      if (step === '__stop__' || !step || step.done) break;
      const chunk = step.value;
      const tk = chunk.choices?.[0]?.text || '';
      const rs = '';
      if (rs) {
        reasoning += rs;
        if (!think) {
          think = document.createElement('details');
          think.className = 'think';
          think.innerHTML = '<summary>Pensamiento</summary><div class="t"></div>';
          body.parentNode.insertBefore(think, body);
        }
        think.querySelector('.t').textContent = reasoning;
      }
      if (tk) { answer += tk; body.textContent = answer.replace(/<think>[\s\S]*?(<\/think>|$)/g, '').trimStart(); }
      if (tk || rs) { count++; if (count % 10 === 0) setStatus(`${agent.name}\u2026 ${count} tokens`); }
      chatEl.scrollTop = chatEl.scrollHeight;
    }
  } catch (e) {
    console.error(e);
    el.classList.add('err');
    body.textContent = 'Error: ' + (e?.message || e);
    el.classList.remove('streaming');
    markActive(null);
    return false;
  }
  el.classList.remove('streaming');
  if (inflight) { const s0 = inflight; Promise.resolve(s0.next ? s0.next() : null).catch(() => {}).finally(() => { if (inflight === s0) inflight = null; }); inflight = null; }
  if (stopRequested) { el.remove(); markActive(null); setStatus('Detenido'); return; }
  answer = answer.replace(/<think>[\s\S]*?<\/think>/g, '').trim();
  answer = answer.replace(/^\s*(?:\*\*)?[A-Za-z\u00c0-\u024f]+:\s*/, '').trim();
  answer = answer.replace(/^Eres un[ae]? (experto|experta|asistente)[^.\n]*[.,]?\s*(y\s+)?/i, '').trim();
  if (!answer) { el.remove(); markActive(null); setStatus('Listo'); return; }
  body.innerHTML = (typeof marked !== 'undefined') ? marked.parse(answer) : esc(answer).replace(/\n/g, '<br>');
  transcript.push({ name: agent.name, text: answer });
  markActive(null);
  setStatus('Listo');
}

let resume = { round: 1, order: null, pos: 0 };

function shuffled(n) {
  const a = [...Array(n).keys()];
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}
function validOrder(o, n) {
  return Array.isArray(o) && o.length === n && new Set(o).size === n &&
    o.every(v => Number.isInteger(v) && v >= 0 && v < n);
}

async function runDebate() {
  running = true;
  stopRequested = false;
  genError = false;
  startBtn.style.display = 'none';
  stopBtn.style.display = 'inline-block';
  topicEl.disabled = true;
  try {
    for (let r = resume.round; r <= CONFIG.rounds && !stopRequested; r++) {
      setStatus(`Ronda ${r}/${CONFIG.rounds}`);
      let order;
      if (r === resume.round && validOrder(resume.order, agents.length)) order = resume.order;
      else order = CONFIG.order === 'rand' ? shuffled(agents.length) : [...Array(agents.length).keys()];
      let startPos = (r === resume.round) ? resume.pos : 0;
      if (startPos >= order.length) startPos = 0;
      for (let p = startPos; p < order.length; p++) {
        if (stopRequested) { resume = { round: r, order, pos: p }; break; }
        const ok = await agentTurn(agents[order[p]]);
        if (ok === false) { genError = true; break; }
        if (stopRequested) { resume = { round: r, order, pos: p }; break; }
      }
      if (genError) break;
      if (!stopRequested) resume = { round: r + 1, order: null, pos: 0 };
    }
    if (!stopRequested) resume = { round: 1, order: null, pos: 0 };
  } finally {
    running = false;
    stopBtn.style.display = 'none';
    startBtn.style.display = 'inline-block';
    startBtn.textContent = 'Continuar debate';
    startBtn.disabled = false;
    topicEl.disabled = false;
    setStatus(genError ? 'Error de generaci\u00f3n: el modelo no respondi\u00f3. Debate detenido.' : (stopRequested ? 'Detenido. Puedes continuar o cambiar de tema.' : 'Debate terminado. Puedes continuar.'));
  }
}

startBtn.addEventListener('click', () => {
  if (!wllama || running) return;
  const newTopic = topicEl.value.trim();
  if (newTopic && newTopic !== topic) {
    topic = newTopic;
    transcript = [];
    chatEl.innerHTML = '';
    resume = { round: 1, order: null, pos: 0 };
    const m = addMsg(null, true);
    m.body.textContent = newTopic;
    transcript.push({ name: null, text: 'Tema propuesto: ' + newTopic });
    recordTopic(newTopic);
  } else if (!topic) {
    topic = 'Tema libre';
  }
  runDebate();
});
stopBtn.addEventListener('click', () => { stopRequested = true; setStatus('Deteniendo\u2026'); });
topicEl.addEventListener('keydown', e => {
  if (e.key === 'Enter') { e.preventDefault(); startBtn.click(); }
});

// --- Temas sugeridos (10 al azar en cada carga) ---
const TOPIC_POOL = [
  'Crea una app de gestión de clientes con FiveWin',
  'Crea un diálogo con campos y validaciones',
  'Soporte técnico: me da este error al compilar o ejecutar',
  'Documentación técnica: explícame esta clase o función',
  'Revisa y mejora este código Harbour',
  'Diagnostica este error y propón una corrección',
  'Crea un ejemplo mínimo reproducible',
  'Diseña un browse con filtros y edición',
  'Trabajar con DBF, SQL y ADS',
  'Migrar código antiguo o de 32 a 64 bits',
];
const suggEl = document.getElementById('topic-sugg');
(function fillSuggestions() {
  const ph = document.createElement('option');
  ph.value = ''; ph.textContent = '\u{1F4A1} 10 tareas de ejemplo\u2026';
  suggEl.appendChild(ph);
  [...TOPIC_POOL].sort(() => Math.random() - .5).slice(0, 10).forEach(t => {
    const o = document.createElement('option');
    o.value = t; o.textContent = t;
    suggEl.appendChild(o);
  });
})();
suggEl.addEventListener('change', () => {
  if (suggEl.value) { topicEl.value = suggEl.value; topicEl.focus(); }
  suggEl.selectedIndex = 0;
});

// --- Settings ---
const settingsPanel = document.getElementById('settings');
document.getElementById('settings-btn').addEventListener('click', () => {
  if (!settingsPanel.classList.contains('open')) {
    document.getElementById('set-repo').value = CONFIG.repo;
    document.getElementById('set-file').value = CONFIG.file;
    document.getElementById('set-ctx').value = CONFIG.nCtx;
    document.getElementById('set-maxtokens').value = CONFIG.maxTokens;
    document.getElementById('set-temp').value = CONFIG.temperature;
    document.getElementById('set-rounds').value = CONFIG.rounds;
    document.getElementById('set-order').value = CONFIG.order;
    document.getElementById('set-agents').value = JSON.stringify(agents, null, 2);
  }
  settingsPanel.classList.toggle('open');
});
document.getElementById('set-preset').addEventListener('change', e => {
  const v = e.target.value; if (!v) return;
  const [r, f] = v.split('|');
  document.getElementById('set-repo').value = r;
  document.getElementById('set-file').value = f;
});
document.getElementById('apply-settings').addEventListener('click', async () => {
  try { agents = JSON.parse(document.getElementById('set-agents').value); }
  catch (e) { alert('JSON de agentes inv\u00e1lido: ' + e.message); return; }
  if (!Array.isArray(agents) || agents.length < 2) { alert('Se necesitan al menos 2 agentes.'); return; }
  persistAgents();
  renderContacts();
  CONFIG.maxTokens = parseInt(document.getElementById('set-maxtokens').value) || CONFIG.maxTokens;
  CONFIG.temperature = parseFloat(document.getElementById('set-temp').value) || CONFIG.temperature;
  CONFIG.rounds = parseInt(document.getElementById('set-rounds').value) || CONFIG.rounds;
  CONFIG.order = document.getElementById('set-order').value === 'rand' ? 'rand' : 'seq';
  const newCtx = parseInt(document.getElementById('set-ctx').value) || CONFIG.nCtx;
  const newRepo = document.getElementById('set-repo').value.trim();
  const newFile = document.getElementById('set-file').value.trim();
  const reload = newCtx !== CONFIG.nCtx || newRepo !== CONFIG.repo || newFile !== CONFIG.file;
  CONFIG.nCtx = newCtx; CONFIG.repo = newRepo; CONFIG.file = newFile;
  settingsPanel.classList.remove('open');
  if (reload || !wllama) { transcript = []; chatEl.innerHTML = ''; await loadModel(CONFIG.repo, CONFIG.file); }
  else setStatus(`Ajustes aplicados. Agentes: ${agents.map(a => a.name).join(', ')}.`);
});

if (CONFIG.autoload) loadModel(CONFIG.repo, CONFIG.file);
else setStatus('Modo manual: carga el modelo desde Ajustes.');
</script>
</body>
</html>