-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cpp
More file actions
7225 lines (6885 loc) · 361 KB
/
server.cpp
File metadata and controls
7225 lines (6885 loc) · 361 KB
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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// =============================================================================
// easyai-server — OpenAI-compatible HTTP server backed by an easyai::Engine.
//
// Goals
// -----
// * Drop-in compatibility with anything that speaks /v1/chat/completions
// (Claude Code's `--api-base`, OpenAI clients, LiteLLM, LangChain…).
// * "Competitor" semantics: when the *client* posts its own `system` message
// and `tools`, those win for that single request — the server-side defaults
// are only used when the request omits them.
// * Built-in toolbelt (datetime / web / fs / bash / rag) auto-
// dispatched server-side when the client does NOT provide tools.
// * Friendly preset commands ("precise", "creative 0.9", "/temp 0.5") inside
// the user message — the server peels them off, applies them, then
// forwards the rest of the message to the model.
// * Tiny single-file webui at GET / with a slider + preset buttons.
//
// Memory hygiene
// --------------
// * One Engine, guarded by std::mutex so requests serialise cleanly across
// httplib's worker threads (no concurrent llama_decode allowed).
// * Per-request: history is *replaced*, not appended — no unbounded growth
// across HTTP calls.
// * Default tool list is owned by the Server (a vector<Tool> built once),
// and we never share Tool objects across mutated requests; we copy the
// vector contents into the engine before each call.
// * Maximum request body size is clamped (default 8 MiB) so a hostile or
// buggy client cannot RAM-bomb the process.
// * Catches std::exception at every HTTP boundary so a malformed request
// can never tear down the server.
// * No raw new/delete anywhere in this file. shared_ptr only where lambdas
// actually need to extend lifetime past handler return.
// =============================================================================
#include "easyai/easyai.hpp"
// llama.cpp common — for incremental chat parsing during SSE streaming.
// Not part of easyai's public API; the server is allowed to reach in.
#include "chat.h"
#include "common.h"
#include "httplib.h" // vendored by llama.cpp
#include "nlohmann/json.hpp" // vendored by llama.cpp
#if defined(EASYAI_BUILD_WEBUI)
// Each *.hpp declares unsigned char NAME[] + unsigned int NAME_len
// where NAME is the filename with '.' / '-' replaced by '_' (xxd convention).
#include "webui_index.html.hpp"
#include "webui_bundle.js.hpp"
#include "webui_bundle.css.hpp"
#include "webui_loading.html.hpp"
#endif
// Brand asset — the AI Box favicon, served at /favicon[.ico|.svg]. Kept
// inline as a raw string literal (not xxd-generated) so the bytes are
// auditable in source and the build skips one codegen step. The canonical
// copy lives at `webui/AI-brain.svg` for external use (docs, external
// rebrand, etc.); this constant is the build-baked source of truth.
constexpr std::string_view kBrandSvg = R"SVG(<svg xmlns="http://www.w3.org/2000/svg" viewBox="-50 -50 300 300" width="300" height="300" role="img" aria-label="AI BOX">
<title>AI BOX</title>
<defs>
<linearGradient id="ai_box_gradient" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#1de9b6"/>
<stop offset="100%" stop-color="#2196f3"/>
</linearGradient>
<filter id="ai_box_aura" x="-10%" y="-10%" width="120%" height="120%">
<feGaussianBlur in="SourceAlpha" stdDeviation="1" result="haloBlur"/>
<feFlood flood-color="#00bcd4" flood-opacity="0.6" result="haloColor"/>
<feComposite in="haloColor" in2="haloBlur" operator="in" result="halo"/>
<feMerge>
<feMergeNode in="halo"/>
<feMergeNode in="SourceGraphic"/>
</feMerge>
</filter>
</defs>
<g filter="url(#ai_box_aura)">
<!-- Outer rounded-square ring (transparent middle via even-odd fill) -->
<path fill="url(#ai_box_gradient)" fill-rule="evenodd" d="M 50 0 H 150 A 50 50 0 0 1 200 50 V 150 A 50 50 0 0 1 150 200 H 50 A 50 50 0 0 1 0 150 V 50 A 50 50 0 0 1 50 0 Z M 56 31 H 144 A 25 25 0 0 1 169 56 V 144 A 25 25 0 0 1 144 169 H 56 A 25 25 0 0 1 31 144 V 56 A 25 25 0 0 1 56 31 Z"/>
<!-- Center mark -->
<rect x="69" y="69" width="62" height="62" rx="13" ry="13" fill="url(#ai_box_gradient)"/>
</g>
</svg>
)SVG";
#include <algorithm>
#include <atomic>
#include <cctype>
#include <cerrno>
#include <climits>
#include <chrono>
#include <cmath>
#include <condition_variable>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <memory>
#include <mutex>
#include <sstream>
#include <string>
#include <string_view>
#include <thread>
#include <dirent.h> // opendir/readdir for fd-count
#include <sys/resource.h>// getrusage, RLIMIT_NOFILE
#include <sys/time.h> // gettimeofday for /proc/stat deltas
#include <unistd.h> // chdir
#include <vector>
// (chat.h pulls in nlohmann::json + a `using json = nlohmann::ordered_json`
// alias, so we don't redeclare those here.)
using nlohmann::ordered_json;
// ============================================================================
// Inline webui
// ----------------------------------------------------------------------------
// A self-contained <500-line single-file chat UI. Talks to /v1/chat/completions
// via the OpenAI shape (no streaming for simplicity — it polls one full reply
// per submit). The preset bar dispatches to /v1/preset which sets server-wide
// defaults for *this UI session only*.
// ============================================================================
constexpr char kWebUI[] = R"HTML(<!doctype html>
<html lang="en"><head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>__EASYAI_TITLE__</title>
<link rel="icon" href="/favicon">
<!-- Optional rich-rendering libs (used when reachable; fallback otherwise) -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css">
<style>
:root {
--bg: #0b0d10;
--bg-elev: #14181e;
--bg-elev2: #1a1f27;
--bg-input: #0f1318;
--bg-hover: #1c2129;
--border: #2a313b;
--border-hi: #3a414b;
--text: #e6edf3;
--text-dim: #8b949e;
--text-faint: #5b626a;
--accent: #1f6feb;
--accent-hi: #2f7ffb;
--accent-dim: #1f6feb33;
--tool: #4fb0ff;
--tool-bg: #102230;
--think: #b97df3;
--think-bg: #1a1330;
--good: #3fb950;
--bad: #f85149;
--warn: #d29922;
--shadow: 0 4px 20px rgba(0,0,0,.4);
}
*, *::before, *::after { box-sizing: border-box; }
html, body { margin: 0; height: 100vh; overflow: hidden; }
body {
font: 14px/1.5 -apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui,
"Segoe UI", Roboto, Helvetica, Arial, sans-serif;
background: var(--bg);
color: var(--text);
-webkit-font-smoothing: antialiased;
}
/* ---------- layout shell ------------------------------------------------ */
#app { display: grid; grid-template-columns: 260px 1fr; height: 100vh; }
#app.no-sidebar { grid-template-columns: 0 1fr; }
@media (max-width: 760px) {
#app { grid-template-columns: 0 1fr; }
#app.show-sidebar { grid-template-columns: 240px 1fr; }
}
/* ---------- sidebar ----------------------------------------------------- */
aside#sidebar {
background: var(--bg-elev);
border-right: 1px solid var(--border);
display: flex; flex-direction: column;
overflow: hidden;
transition: width .15s ease;
}
.no-sidebar #sidebar { display: none; }
@media (max-width: 760px) { #sidebar { display: none; } .show-sidebar #sidebar { display: flex; } }
#sidebar .head {
padding: .55rem .55rem; border-bottom: 1px solid var(--border);
display: flex; gap: .4rem; align-items: center;
}
#newChatBtn {
flex: 1; background: transparent; color: var(--text);
border: 1px dashed var(--border-hi); border-radius: 6px;
padding: .45rem .6rem; font: inherit; cursor: pointer;
display: flex; align-items: center; gap: .4rem;
transition: background .12s, border-color .12s;
}
#newChatBtn:hover { background: var(--bg-hover); border-color: var(--accent); }
#newChatBtn .plus { font-weight: 700; color: var(--accent); }
#convList { list-style: none; margin: 0; padding: .35rem; overflow-y: auto; flex: 1; }
.conv-item {
display: flex; align-items: center; gap: .4rem;
padding: .45rem .55rem; border-radius: 6px;
cursor: pointer; color: var(--text-dim); font-size: .85rem;
position: relative;
}
.conv-item:hover { background: var(--bg-hover); color: var(--text); }
.conv-item.active { background: var(--accent-dim); color: var(--text); }
.conv-item .title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.conv-item .stamp { font-size: .68rem; color: var(--text-faint); flex-shrink: 0; }
.conv-item .del {
display: none; background: none; border: 0; color: var(--text-dim);
font-size: .9rem; cursor: pointer; padding: 0 .2rem; line-height: 1;
}
.conv-item:hover .del { display: inline-block; }
.conv-item .del:hover { color: var(--bad); }
#sidebar .foot {
border-top: 1px solid var(--border); padding: .45rem .55rem;
font-size: .7rem; color: var(--text-faint);
display: flex; align-items: center; gap: .4rem;
}
/* ---------- main / header ----------------------------------------------- */
main { display: flex; flex-direction: column; min-width: 0; }
header.topbar {
padding: .55rem .85rem;
background: var(--bg-elev);
border-bottom: 1px solid var(--border);
display: flex; align-items: center; gap: .55rem; flex-wrap: wrap;
}
header.topbar h1 { font-size: 1rem; margin: 0; font-weight: 600; letter-spacing: .01em; }
.pill {
font-size: .7rem; color: var(--text-dim);
padding: .15rem .55rem; border: 1px solid var(--border); border-radius: 999px;
white-space: nowrap;
}
.icon-btn {
background: transparent; color: var(--text-dim); border: 1px solid transparent;
border-radius: 6px; padding: .25rem .45rem; cursor: pointer; font-size: 1rem;
transition: background .12s, color .12s, border-color .12s;
}
.icon-btn:hover { background: var(--bg-hover); color: var(--text); border-color: var(--border); }
.spacer { flex: 1; }
/* ---------- chat area --------------------------------------------------- */
#chat { flex: 1; overflow-y: auto; padding: 1.2rem 0 .8rem; }
.empty {
height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center;
color: var(--text-faint); padding: 2rem; text-align: center; gap: .6rem;
}
.empty h2 { color: var(--text-dim); font-weight: 500; margin: 0; }
.empty .ex { display: flex; flex-wrap: wrap; gap: .4rem; justify-content: center; max-width: 540px; }
.empty .ex button {
background: var(--bg-elev); color: var(--text-dim);
border: 1px solid var(--border); border-radius: 999px;
padding: .35rem .8rem; font-size: .8rem; cursor: pointer;
}
.empty .ex button:hover { color: var(--text); border-color: var(--accent); }
.msg { max-width: 78ch; margin: 0 auto 1.4rem; padding: 0 1.2rem; }
.msg .role {
font-size: .68rem; color: var(--text-faint); text-transform: uppercase;
letter-spacing: .08em; margin-bottom: .25rem;
display: flex; align-items: center; gap: .5rem;
}
.msg .role .actions { margin-left: auto; opacity: 0; transition: opacity .12s; }
.msg:hover .role .actions { opacity: 1; }
.msg .role .actions button {
background: none; border: 0; color: var(--text-dim); padding: 0 .3rem;
cursor: pointer; font-size: .75rem; border-radius: 3px;
}
.msg .role .actions button:hover { color: var(--text); background: var(--bg-hover); }
.msg.user .body {
background: #0d2543; border: 1px solid #1f4a77;
padding: .6rem .85rem; border-radius: 8px;
white-space: pre-wrap; word-wrap: break-word;
}
.msg.assistant .content { padding: .15rem 0; word-wrap: break-word; overflow-wrap: anywhere; }
.msg.assistant .content p { margin: .35rem 0; }
.msg.assistant .content p:first-child { margin-top: 0; }
.msg.assistant .content p:last-child { margin-bottom: 0; }
.msg.assistant .content h1, .msg.assistant .content h2, .msg.assistant .content h3 {
font-size: 1rem; margin: 1rem 0 .35rem; font-weight: 600;
}
.msg.assistant .content h1 { font-size: 1.15rem; }
.msg.assistant .content h2 { font-size: 1.05rem; }
.msg.assistant .content ul, .msg.assistant .content ol { padding-left: 1.4rem; margin: .35rem 0; }
.msg.assistant .content li { margin: .15rem 0; }
.msg.assistant .content blockquote {
border-left: 3px solid var(--border); margin: .4rem 0; padding: .1rem .8rem; color: var(--text-dim);
}
.msg.assistant .content pre {
background: #0a0d11; border: 1px solid var(--border);
padding: .65rem .8rem; border-radius: 6px;
overflow-x: auto; font-size: .85em; line-height: 1.45; margin: .5rem 0;
}
.msg.assistant .content code {
background: var(--bg-input); padding: .1rem .35rem;
border-radius: 3px; font-size: .88em;
font-family: ui-monospace, "SF Mono", Menlo, monospace;
}
.msg.assistant .content pre code { background: transparent; padding: 0; font-size: 1em; }
.msg.assistant .content a { color: var(--accent); text-decoration: none; }
.msg.assistant .content a:hover { text-decoration: underline; }
.msg.assistant .content table { border-collapse: collapse; margin: .5rem 0; }
.msg.assistant .content th, .msg.assistant .content td {
border: 1px solid var(--border); padding: .25rem .5rem; font-size: .9em;
}
.msg.assistant .content th { background: var(--bg-elev); font-weight: 600; }
/* thinking + tool cards keep their own visual identity */
.thinking {
border: 1px solid var(--think-bg); background: var(--think-bg);
border-left: 3px solid var(--think); border-radius: 6px;
margin: .5rem 0; padding: .35rem .6rem; font-size: .85em; color: var(--text-dim);
}
.thinking summary {
cursor: pointer; color: var(--think); font-weight: 600;
outline: none; user-select: none; list-style: none;
}
.thinking summary::-webkit-details-marker { display: none; }
.thinking summary::before { content: "▸ "; color: var(--think); font-weight: 700; }
.thinking[open] summary::before { content: "▾ "; }
.thinking[open] summary { margin-bottom: .4rem; }
.thinking .think-body {
white-space: pre-wrap; font-family: ui-monospace, "SF Mono", Menlo, monospace;
font-size: .82rem; line-height: 1.5; max-height: 24em; overflow-y: auto;
}
.tool-card {
border: 1px solid var(--tool-bg); background: var(--tool-bg);
border-left: 3px solid var(--tool); border-radius: 6px;
margin: .5rem 0; padding: .45rem .65rem;
font-family: ui-monospace, "SF Mono", Menlo, monospace; font-size: .8rem;
}
.tool-card.error { border-left-color: var(--bad); background: #22151a; }
.tool-card .head { display: flex; align-items: baseline; gap: .4rem; flex-wrap: wrap; }
.tool-card .name { color: var(--tool); font-weight: 600; }
.tool-card.error .name { color: var(--bad); }
.tool-card .args { color: var(--text-dim); word-break: break-all; }
.tool-card .result {
color: var(--text); margin-top: .35rem; white-space: pre-wrap;
max-height: 16em; overflow-y: auto; padding-top: .35rem;
border-top: 1px dashed var(--border);
}
.tool-card .result.pending { color: var(--text-dim); font-style: italic; }
.cursor {
display: inline-block; width: .5em; height: 1em;
background: var(--text); animation: blink 1s steps(1, end) infinite;
vertical-align: text-bottom; margin-left: 1px;
}
@keyframes blink { 50% { opacity: 0; } }
.stats {
font-size: .68rem; color: var(--text-faint); margin-top: .35rem;
font-family: ui-monospace, "SF Mono", Menlo, monospace;
}
.error-msg {
color: var(--bad); background: #22151a;
border: 1px solid #6a2a31; border-radius: 6px;
padding: .5rem .7rem; font-size: .9em;
}
/* ---------- input bar --------------------------------------------------- */
#inputWrap {
border-top: 1px solid var(--border); background: var(--bg-elev);
padding: .55rem .85rem .7rem; position: relative;
}
#inputBar { display: flex; gap: .45rem; align-items: flex-end; }
#textArea {
flex: 1; resize: none; min-height: 2.4rem; max-height: 30vh;
padding: .55rem .7rem;
background: var(--bg-input); color: var(--text);
border: 1px solid var(--border); border-radius: 8px;
font: inherit; line-height: 1.5;
}
#textArea:focus { outline: 2px solid var(--accent-dim); border-color: var(--accent); }
#sendBtn, #stopBtn {
background: var(--accent); color: #fff; border: 0;
border-radius: 8px; padding: 0 1.05rem; cursor: pointer; font-weight: 600;
height: 2.4rem; align-self: flex-end;
}
#sendBtn:hover { background: var(--accent-hi); }
#sendBtn:disabled { opacity: .55; cursor: wait; }
#stopBtn { background: var(--bad); }
#stopBtn:hover { filter: brightness(1.1); }
#settingsToggle, #sidebarToggle {
background: var(--bg-input); color: var(--text-dim);
border: 1px solid var(--border); border-radius: 8px;
padding: 0 .65rem; cursor: pointer; font-size: 1rem;
height: 2.4rem; align-self: flex-end;
}
#settingsToggle:hover, #sidebarToggle:hover { background: var(--bg-hover); color: var(--text); }
#settingsToggle.active { color: var(--accent); border-color: var(--accent); }
#settingsHint {
color: var(--text-faint); font-size: .68rem; padding-top: .3rem;
display: flex; gap: 1rem; flex-wrap: wrap;
}
#settingsHint .pill { font-size: .65rem; padding: .05rem .45rem; cursor: pointer; }
#settingsHint .pill:hover { color: var(--text); border-color: var(--border-hi); }
/* settings popover */
#settingsPanel {
position: absolute; bottom: calc(100% + 2px); right: .85rem;
width: min(380px, calc(100vw - 1.7rem));
background: var(--bg-elev2); color: var(--text);
border: 1px solid var(--border-hi); border-radius: 10px;
box-shadow: var(--shadow); padding: .7rem .85rem;
display: none; z-index: 50;
}
#settingsPanel.open { display: block; }
#settingsPanel h3 {
font-size: .82rem; margin: 0 0 .55rem; font-weight: 600;
color: var(--text-dim); text-transform: uppercase; letter-spacing: .06em;
}
.preset-row {
display: flex; flex-wrap: wrap; gap: .25rem;
margin-bottom: .65rem;
}
.preset-row button {
background: transparent; color: var(--text-dim);
border: 1px solid var(--border); border-radius: 999px;
padding: .25rem .65rem; cursor: pointer; font-size: .75rem;
}
.preset-row button:hover { background: var(--bg-hover); color: var(--text); }
.preset-row button.active { background: var(--accent); border-color: var(--accent); color: white; }
.slider-row {
display: grid; grid-template-columns: 80px 1fr 56px;
gap: .55rem; align-items: center; margin: .35rem 0;
font-size: .82rem;
}
.slider-row label { color: var(--text-dim); }
.slider-row input[type=range] { width: 100%; accent-color: var(--accent); }
.slider-row input[type=number] {
width: 100%; background: var(--bg-input); color: var(--text);
border: 1px solid var(--border); border-radius: 4px; padding: .15rem .3rem;
font: inherit; font-size: .82rem; text-align: right;
}
#settingsPanel .reset-link {
font-size: .72rem; color: var(--text-dim); text-decoration: underline;
background: none; border: 0; cursor: pointer; padding: 0; margin-top: .3rem;
}
/* small helper: invisible on narrow screens */
.hide-narrow { display: inline-flex; }
@media (max-width: 760px) { .hide-narrow { display: none; } }
</style></head>
<body>
<div id="app" class="show-sidebar">
<aside id="sidebar">
<div class="head">
<button id="newChatBtn"><span class="plus">+</span> New chat</button>
</div>
<ul id="convList"></ul>
<div class="foot">
<span id="model" class="pill">…</span>
<span id="backend" class="pill"></span>
<span id="ntools" class="pill"></span>
</div>
</aside>
<main>
<header class="topbar">
<button class="icon-btn" id="sidebarToggle" title="Toggle sidebar">☰</button>
<h1>__EASYAI_TITLE__</h1>
<span class="spacer"></span>
<button class="icon-btn hide-narrow" id="thinkToggleHdr" title="Show / hide reasoning blocks">◐ thinking</button>
</header>
<div id="chat"></div>
<div id="inputWrap">
<div id="settingsPanel">
<h3>preset</h3>
<div class="preset-row" id="presetRow">
<button data-p="deterministic">deterministic</button>
<button data-p="precise" class="active">precise</button>
<button data-p="balanced">balanced</button>
<button data-p="creative">creative</button>
<button data-p="wild">wild</button>
</div>
<h3>sampling</h3>
<div class="slider-row">
<label for="sTemp">temperature</label>
<input type="range" id="sTemp" min="0" max="2" step="0.05" value="0.7">
<input type="number" id="sTempN" min="0" max="2" step="0.05" value="0.7">
</div>
<div class="slider-row">
<label for="sTopP">top_p</label>
<input type="range" id="sTopP" min="0" max="1" step="0.01" value="0.95">
<input type="number" id="sTopPN" min="0" max="1" step="0.01" value="0.95">
</div>
<div class="slider-row">
<label for="sTopK">top_k</label>
<input type="range" id="sTopK" min="1" max="100" step="1" value="40">
<input type="number" id="sTopKN" min="1" max="100" step="1" value="40">
</div>
<div class="slider-row">
<label for="sMinP">min_p</label>
<input type="range" id="sMinP" min="0" max="0.5" step="0.01" value="0.05">
<input type="number" id="sMinPN" min="0" max="0.5" step="0.01" value="0.05">
</div>
<div class="slider-row">
<label for="sMaxTok">max_tokens</label>
<input type="range" id="sMaxTok" min="0" max="4096" step="64" value="0">
<input type="number" id="sMaxTokN" min="0" max="32768" step="1" value="0">
</div>
<button class="reset-link" id="settingsReset">reset to balanced</button>
</div>
<div id="inputBar">
<button id="settingsToggle" title="Sampling settings">⚙</button>
<textarea id="textArea" rows="1" placeholder="Type a message…"></textarea>
<button id="stopBtn" hidden>stop</button>
<button id="sendBtn">send</button>
</div>
<div id="settingsHint">
<span>Ctrl/⌘+Enter to send</span>
<span class="pill" data-quick="0">temp 0.0 (deterministic)</span>
<span class="pill" data-quick="0.7">temp 0.7 (balanced)</span>
<span class="pill" data-quick="1.0">temp 1.0 (creative)</span>
<span style="color:var(--text-faint)">or inline: <code>creative 0.9 …</code></span>
</div>
</div>
</main>
</div>
<!-- markdown lib (loaded async, with graceful fallback) -->
<script src="https://cdn.jsdelivr.net/npm/marked@12/marked.min.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" defer></script>
<script>
"use strict";
// ============================================================================
// helpers
// ============================================================================
const $ = (s, r=document) => r.querySelector(s);
const $$ = (s, r=document) => Array.from(r.querySelectorAll(s));
const escHTML = s => String(s).replace(/[&<>"']/g, c => ({
'&':'&','<':'<','>':'>','"':'"',"'":'''
}[c]));
function relTime(ts){
const s = (Date.now() - ts) / 1000;
if (s < 60) return Math.floor(s) + 's';
if (s < 3600) return Math.floor(s/60) + 'm';
if (s < 86400) return Math.floor(s/3600) + 'h';
if (s < 86400*7) return Math.floor(s/86400) + 'd';
return new Date(ts).toLocaleDateString();
}
// Tiny markdown fallback used when marked.js failed to load (offline boxes).
function tinyMD(s){
if (!s) return '';
let html = escHTML(s);
const parked = [];
const park = f => (parked.push(f), `\u0001${parked.length-1}\u0001`);
html = html.replace(/```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/g, (_, l, c) =>
park(`<pre><code class="lang-${escHTML(l)}">${c}</code></pre>`));
html = html.replace(/`([^`\n]+)`/g, (_, c) => park(`<code>${c}</code>`));
html = html.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, t, u) =>
park(`<a href="${u}" target="_blank" rel="noopener">${t}</a>`));
html = html.replace(/\*\*([^\*\n]+?)\*\*/g, '<strong>$1</strong>');
html = html.replace(/(^|[^\*])\*([^\*\n]+?)\*(?!\*)/g, '$1<em>$2</em>');
html = html.replace(/(\bhttps?:\/\/[^\s<]+?)([.,;:!?)\]]*)(?=\s|$)/g,
(_, u, t) => park(`<a href="${u}" target="_blank" rel="noopener">${u}</a>`) + t);
html = html.replace(/\n/g, '<br>');
html = html.replace(/\u0001(\d+)\u0001/g, (_, i) => parked[+i]);
return html;
}
function renderMD(s){
if (window.marked) {
try {
// Configure once.
if (!window._mdReady) {
window.marked.setOptions({ breaks: true, gfm: true });
window._mdReady = true;
}
let html = window.marked.parse(s || '');
// Run highlight.js on freshly built code blocks.
if (window.hljs) {
const tmp = document.createElement('div');
tmp.innerHTML = html;
$$('pre code', tmp).forEach(b => {
try { window.hljs.highlightElement(b); } catch {}
});
html = tmp.innerHTML;
}
return html;
} catch (e) {
console.warn('markdown fallback', e);
}
}
return tinyMD(s);
}
// ============================================================================
// IndexedDB-backed conversation storage
// ============================================================================
const DB_NAME = 'easyai';
const STORE = 'conversations';
function openDB(){
return new Promise((res, rej) => {
const req = indexedDB.open(DB_NAME, 1);
req.onupgradeneeded = () => req.result.createObjectStore(STORE, { keyPath: 'id' });
req.onsuccess = () => res(req.result);
req.onerror = () => rej(req.error);
});
}
async function dbAll(){
const db = await openDB();
return new Promise((res, rej) => {
const tx = db.transaction(STORE, 'readonly');
const req = tx.objectStore(STORE).getAll();
req.onsuccess = () => res(req.result || []);
req.onerror = () => rej(req.error);
});
}
async function dbPut(conv){
const db = await openDB();
return new Promise((res, rej) => {
const tx = db.transaction(STORE, 'readwrite');
tx.objectStore(STORE).put(conv);
tx.oncomplete = () => res();
tx.onerror = () => rej(tx.error);
});
}
async function dbDel(id){
const db = await openDB();
return new Promise((res, rej) => {
const tx = db.transaction(STORE, 'readwrite');
tx.objectStore(STORE).delete(id);
tx.oncomplete = () => res();
tx.onerror = () => rej(tx.error);
});
}
// ============================================================================
// app state
// ============================================================================
const state = {
convs: [], // [{id, title, created, updated, messages, settings}]
currentId: null,
showThinking: true,
abort: null, // current AbortController
settings: loadSettings(), // sampling defaults persisted in localStorage
};
const PRESETS = {
deterministic: { temperature: 0.0, top_p: 1.0, top_k: 1, min_p: 0.0 },
precise: { temperature: 0.2, top_p: 0.95, top_k: 40, min_p: 0.10 },
balanced: { temperature: 0.7, top_p: 0.95, top_k: 40, min_p: 0.05 },
creative: { temperature: 1.0, top_p: 0.95, top_k: 40, min_p: 0.05 },
wild: { temperature: 1.4, top_p: 0.98, top_k: 60, min_p: 0.0 },
};
function loadSettings(){
try {
const j = JSON.parse(localStorage.getItem('easyai-settings') || '{}');
return Object.assign({
preset: 'precise',
temperature: PRESETS.precise.temperature,
top_p: PRESETS.precise.top_p,
top_k: PRESETS.precise.top_k,
min_p: PRESETS.precise.min_p,
max_tokens: 0, // 0 = no client cap
}, j);
} catch { return loadDefaultSettings(); }
}
function loadDefaultSettings(){
return Object.assign({ preset:'precise', max_tokens: 0 }, PRESETS.precise);
}
function saveSettings(){ localStorage.setItem('easyai-settings', JSON.stringify(state.settings)); }
function newConv(){
return {
id: (crypto && crypto.randomUUID) ? crypto.randomUUID() : (Date.now() + '-' + Math.random()),
title: 'New chat',
created: Date.now(),
updated: Date.now(),
messages: [],
};
}
async function loadAllConvs(){
state.convs = (await dbAll().catch(() => [])).sort((a,b) => b.updated - a.updated);
if (state.convs.length === 0) {
const c = newConv();
state.convs.push(c);
state.currentId = c.id;
await dbPut(c).catch(()=>{});
} else {
state.currentId = state.convs[0].id;
}
}
const currentConv = () => state.convs.find(c => c.id === state.currentId);
// ============================================================================
// rendering — sidebar
// ============================================================================
function renderSidebar(){
const list = $('#convList');
list.innerHTML = '';
for (const c of state.convs) {
const li = document.createElement('li');
li.className = 'conv-item' + (c.id === state.currentId ? ' active' : '');
li.innerHTML = `
<span class="title"></span>
<span class="stamp"></span>
<button class="del" title="Delete">×</button>`;
$('.title', li).textContent = c.title || 'untitled';
$('.stamp', li).textContent = relTime(c.updated);
li.onclick = e => {
if (e.target.classList.contains('del')) return;
switchConv(c.id);
};
$('.del', li).onclick = async () => {
if (!confirm('Delete this conversation?')) return;
await dbDel(c.id).catch(()=>{});
state.convs = state.convs.filter(x => x.id !== c.id);
if (state.currentId === c.id) {
if (state.convs.length === 0) {
const nc = newConv(); state.convs.push(nc); state.currentId = nc.id;
await dbPut(nc).catch(()=>{});
} else state.currentId = state.convs[0].id;
}
renderSidebar(); renderChat();
};
list.appendChild(li);
}
}
function switchConv(id){
if (state.abort) state.abort.abort();
state.currentId = id;
renderSidebar();
renderChat();
}
async function startNewConv(){
if (state.abort) state.abort.abort();
const c = newConv();
state.convs.unshift(c);
state.currentId = c.id;
await dbPut(c).catch(()=>{});
renderSidebar();
renderChat();
$('#textArea').focus();
}
// ============================================================================
// rendering — chat
// ============================================================================
const chatEl = $('#chat');
function renderChat(){
const c = currentConv();
chatEl.innerHTML = '';
if (!c || c.messages.length === 0) {
chatEl.innerHTML = `
<div class="empty">
<h2>How can I help?</h2>
<div class="ex">
<button data-pp="What time is it now?">What time is it now?</button>
<button data-pp="Search the web for the latest llama.cpp release and summarise.">Latest llama.cpp release</button>
<button data-pp="creative 0.9 write me a haiku about silicon">creative 0.9 haiku</button>
<button data-pp="List the files in the current directory.">List files</button>
</div>
</div>`;
$$('.empty .ex button').forEach(b => b.onclick = () => {
$('#textArea').value = b.dataset.pp;
$('#textArea').focus();
});
return;
}
for (const m of c.messages) renderMessage(m);
chatEl.scrollTop = chatEl.scrollHeight;
}
function appendUserMsg(text){
const el = document.createElement('div');
el.className = 'msg user';
el.innerHTML = `<div class="role">you</div><div class="body"></div>`;
$('.body', el).textContent = text;
chatEl.appendChild(el);
chatEl.scrollTop = chatEl.scrollHeight;
return el;
}
function renderMessage(m){
if (m.role === 'user') {
appendUserMsg(m.content);
return;
}
if (m.role === 'assistant') {
const turn = new AssistantTurn(state.showThinking, /*live=*/false);
turn.raw = m.content || '';
if (m.toolCards) {
for (const t of m.toolCards) turn.replayToolCard(t);
}
turn.finish('stop');
}
}
// ============================================================================
// AssistantTurn — one streaming reply
// ============================================================================
class AssistantTurn {
constructor(showThinking, live=true){
this.raw = '';
this.tokens = 0;
this.startMs = performance.now();
this.showThinking = showThinking;
this.toolCards = []; // {name, args, result, error}
this.pendingByName = new Map();
this._done = !live;
this.el = document.createElement('div');
this.el.className = 'msg assistant';
this.el.innerHTML = `
<div class="role">
<span>assistant</span>
<span class="actions">
<button class="copy" title="Copy">copy</button>
</span>
</div>
<div class="content"></div>
<div class="stats"></div>`;
this.contentEl = $('.content', this.el);
this.statsEl = $('.stats', this.el);
chatEl.appendChild(this.el);
chatEl.scrollTop = chatEl.scrollHeight;
$('.copy', this.el).onclick = () => {
const t = this.finalText();
navigator.clipboard?.writeText(t).catch(()=>{});
};
}
addContent(piece){
this.tokens += 1;
this.raw += piece;
this.render();
}
render(){
// Split out <think>...</think> blocks; render content with markdown.
let cleaned = '';
const thinks = [];
const re = /<think(?:ing)?>([\s\S]*?)(?:<\/think(?:ing)?>|$)/g;
let m, last = 0;
while ((m = re.exec(this.raw)) !== null) {
cleaned += this.raw.slice(last, m.index);
thinks.push(m[1]);
last = m.index + m[0].length;
}
cleaned += this.raw.slice(last);
let thinkEl = $(':scope > .thinking', this.el);
if (thinks.length) {
const txt = thinks.join('\n\n— —\n\n');
if (!thinkEl) {
thinkEl = document.createElement('details');
thinkEl.className = 'thinking';
if (this.showThinking) thinkEl.open = true;
thinkEl.innerHTML = '<summary>Thinking</summary><div class="think-body"></div>';
this.el.insertBefore(thinkEl, this.contentEl);
}
$('.think-body', thinkEl).textContent = txt;
}
this.contentEl.innerHTML = renderMD(cleaned) +
(this._done ? '' : '<span class="cursor"></span>');
chatEl.scrollTop = chatEl.scrollHeight;
}
// server-side prompt-eval completion (mirrors llama-server's
// "prompt eval time" stderr line). Renders a single dim line
// above the content area so the user sees the moment ingestion
// finished and generation starts. Replaces a previous prompt-
// eval line in the same turn (multi-hop turns get one event per
// generate() call; only the most recent matters for the user).
addPromptEval(evt){
let el = $(':scope > .prompt-eval', this.el);
if (!el) {
el = document.createElement('div');
el.className = 'prompt-eval';
el.style.cssText = 'margin:.4rem 0;padding:.2rem .55rem;'
+ 'border-left:2px solid #d29922;'
+ 'background:rgba(210,153,34,.08);'
+ 'border-radius:4px;font-size:.75rem;color:#d29922;'
+ 'font-family:ui-monospace,SFMono-Regular,Menlo,monospace;';
this.el.insertBefore(el, this.contentEl);
}
const tps = evt.tokens_per_second || 0;
const ms = evt.prompt_ms || 0;
const n = evt.n_tokens || 0;
const cached = evt.n_cached || 0;
el.textContent = '* ' + n + ' tok'
+ (cached > 0 ? ' (' + cached + ' cached)' : '')
+ ' · ' + Math.round(ms) + ' ms · ' + tps.toFixed(1) + ' t/s';
}
// server-side tool dispatch — card with running placeholder
addToolCall(evt){
const card = document.createElement('div');
card.className = 'tool-card';
let argStr = '';
try { argStr = JSON.stringify(JSON.parse(evt.arguments)); }
catch { argStr = evt.arguments || ''; }
card.innerHTML = `
<div class="head">
<span class="name"></span>
<span class="args"></span>
</div>
<div class="result pending">…running…</div>`;
$('.name', card).textContent = evt.name;
$('.args', card).textContent = '(' + argStr + ')';
this.el.insertBefore(card, this.contentEl);
this.toolCards.push({ el: card, name: evt.name, args: argStr });
if (!this.pendingByName.has(evt.name)) this.pendingByName.set(evt.name, []);
this.pendingByName.get(evt.name).push(card);
chatEl.scrollTop = chatEl.scrollHeight;
}
addToolResult(evt){
const stack = this.pendingByName.get(evt.name);
if (!stack || !stack.length) return;
const card = stack.shift();
const resEl = $('.result', card);
resEl.classList.remove('pending');
resEl.textContent = evt.content || '';
if (evt.is_error) card.classList.add('error');
// Keep a record for replay/persistence.
const rec = this.toolCards.find(t => t.el === card);
if (rec) { rec.result = evt.content || ''; rec.error = !!evt.is_error; }
}
// For client-tools mode (rare from the webui).
addClientToolCalls(tcs){
for (const tc of tcs) {
if (!tc.function) continue;
this.addToolCall({
name: tc.function.name || '?',
arguments: tc.function.arguments || '{}',
id: tc.id || ''
});
const stack = this.pendingByName.get(tc.function.name);
if (stack && stack.length) {
const card = stack.shift();
$('.result', card).classList.remove('pending');
$('.result', card).textContent = '(forwarded to client for execution)';
$('.result', card).style.fontStyle = 'italic';
}
}
}
// Used during conversation replay (loading from IDB).
replayToolCard(t){
const card = document.createElement('div');
card.className = 'tool-card' + (t.error ? ' error' : '');
card.innerHTML = `
<div class="head">
<span class="name"></span>
<span class="args"></span>
</div>
<div class="result"></div>`;
$('.name', card).textContent = t.name;
$('.args', card).textContent = '(' + (t.args || '') + ')';
$('.result', card).textContent = t.result || '';
this.el.insertBefore(card, this.contentEl);
this.toolCards.push(t);
}
finish(reason){
this._done = true;
const elapsed = (performance.now() - this.startMs) / 1000;
if (this.tokens > 0) {
const tps = this.tokens / Math.max(elapsed, 0.001);
this.statsEl.textContent = `${this.tokens} chunks · ${elapsed.toFixed(2)}s · ${tps.toFixed(1)} chunks/s · ${reason}`;
}
this.render();
}
fail(msg){
this._done = true;
this.contentEl.innerHTML = `<div class="error-msg">⚠︎ ${escHTML(msg)}</div>`;
}
// Strip <think> blocks — what we save into history for the next request.