forked from antirez/ds4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathds4_server.c
More file actions
7676 lines (7093 loc) · 263 KB
/
ds4_server.c
File metadata and controls
7676 lines (7093 loc) · 263 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
#include "ds4.h"
/* OpenAI/Anthropic compatible local server.
*
* HTTP is intentionally simple: each client connection is handled by a small
* blocking thread that parses one request, then queues a job to the single
* Metal worker. The worker owns the ds4_session and therefore owns all live KV
* cache state. That keeps session reuse, disk checkpointing, and future
* batching decisions in one place instead of spreading graph mutations across
* client threads. */
#include <arpa/inet.h>
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <netinet/in.h>
#include <poll.h>
#include <pthread.h>
#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
static volatile sig_atomic_t g_stop_requested = 0;
static volatile sig_atomic_t g_listen_fd = -1;
#define DS4_SERVER_IO_TIMEOUT_SEC 10
#define DS4_SERVER_SEND_STALL_TIMEOUT_MS 2000
static void stop_signal_handler(int sig) {
(void)sig;
if (g_stop_requested) _exit(130);
g_stop_requested = 1;
if (g_listen_fd >= 0) {
int fd = (int)g_listen_fd;
g_listen_fd = -1;
close(fd);
}
}
typedef struct {
char *ptr;
size_t len;
size_t cap;
} buf;
static void die(const char *msg) {
fprintf(stderr, "ds4-server: %s\n", msg);
exit(1);
}
static void *xmalloc(size_t n) {
void *p = malloc(n ? n : 1);
if (!p) die("out of memory");
return p;
}
static void *xrealloc(void *p, size_t n) {
p = realloc(p, n ? n : 1);
if (!p) die("out of memory");
return p;
}
static char *xstrdup(const char *s) {
size_t n = strlen(s);
char *p = xmalloc(n + 1);
memcpy(p, s, n + 1);
return p;
}
static char *xstrndup(const char *s, size_t n) {
char *p = xmalloc(n + 1);
memcpy(p, s, n);
p[n] = '\0';
return p;
}
static void buf_reserve(buf *b, size_t add) {
if (add > SIZE_MAX - b->len - 1) die("buffer overflow");
size_t need = b->len + add + 1;
if (need <= b->cap) return;
size_t cap = b->cap ? b->cap * 2 : 256;
while (cap < need) cap *= 2;
b->ptr = xrealloc(b->ptr, cap);
b->cap = cap;
}
static void buf_append(buf *b, const void *p, size_t n) {
buf_reserve(b, n);
memcpy(b->ptr + b->len, p, n);
b->len += n;
b->ptr[b->len] = '\0';
}
static void buf_putc(buf *b, char c) {
buf_append(b, &c, 1);
}
static void buf_puts(buf *b, const char *s) {
buf_append(b, s, strlen(s));
}
static void buf_printf(buf *b, const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
va_list ap2;
va_copy(ap2, ap);
int n = vsnprintf(NULL, 0, fmt, ap);
va_end(ap);
if (n < 0) die("vsnprintf failed");
buf_reserve(b, (size_t)n);
vsnprintf(b->ptr + b->len, b->cap - b->len, fmt, ap2);
va_end(ap2);
b->len += (size_t)n;
}
static char *buf_take(buf *b) {
if (!b->ptr) return xstrdup("");
char *p = b->ptr;
memset(b, 0, sizeof(*b));
return p;
}
static void buf_free(buf *b) {
free(b->ptr);
memset(b, 0, sizeof(*b));
}
static void json_ws(const char **p) {
while (**p && isspace((unsigned char)**p)) (*p)++;
}
static bool json_lit(const char **p, const char *lit) {
size_t n = strlen(lit);
if (strncmp(*p, lit, n) != 0) return false;
*p += n;
return true;
}
static int json_hex(char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return 10 + c - 'a';
if (c >= 'A' && c <= 'F') return 10 + c - 'A';
return -1;
}
static void utf8_put(buf *b, uint32_t cp) {
if (cp <= 0x7f) {
buf_putc(b, (char)cp);
} else if (cp <= 0x7ff) {
buf_putc(b, (char)(0xc0 | (cp >> 6)));
buf_putc(b, (char)(0x80 | (cp & 0x3f)));
} else if (cp <= 0xffff) {
buf_putc(b, (char)(0xe0 | (cp >> 12)));
buf_putc(b, (char)(0x80 | ((cp >> 6) & 0x3f)));
buf_putc(b, (char)(0x80 | (cp & 0x3f)));
} else {
buf_putc(b, (char)(0xf0 | (cp >> 18)));
buf_putc(b, (char)(0x80 | ((cp >> 12) & 0x3f)));
buf_putc(b, (char)(0x80 | ((cp >> 6) & 0x3f)));
buf_putc(b, (char)(0x80 | (cp & 0x3f)));
}
}
static bool json_u16(const char **p, uint32_t *out) {
if ((*p)[0] != '\\' || (*p)[1] != 'u') return false;
uint32_t cp = 0;
for (int i = 0; i < 4; i++) {
int h = json_hex((*p)[2 + i]);
if (h < 0) return false;
cp = (cp << 4) | (uint32_t)h;
}
*p += 6;
*out = cp;
return true;
}
static bool json_string(const char **p, char **out) {
json_ws(p);
if (**p != '"') return false;
(*p)++;
buf b = {0};
while (**p && **p != '"') {
unsigned char c = (unsigned char)*(*p)++;
if (c != '\\') {
buf_putc(&b, (char)c);
continue;
}
c = (unsigned char)*(*p)++;
switch (c) {
case '"': buf_putc(&b, '"'); break;
case '\\': buf_putc(&b, '\\'); break;
case '/': buf_putc(&b, '/'); break;
case 'b': buf_putc(&b, '\b'); break;
case 'f': buf_putc(&b, '\f'); break;
case 'n': buf_putc(&b, '\n'); break;
case 'r': buf_putc(&b, '\r'); break;
case 't': buf_putc(&b, '\t'); break;
case 'u': {
*p -= 2;
uint32_t cp = 0, lo = 0;
if (!json_u16(p, &cp)) goto fail;
if (cp >= 0xd800 && cp <= 0xdbff && json_u16(p, &lo) && lo >= 0xdc00 && lo <= 0xdfff) {
cp = 0x10000u + ((cp - 0xd800u) << 10) + (lo - 0xdc00u);
}
utf8_put(&b, cp);
break;
}
default:
goto fail;
}
}
if (**p != '"') goto fail;
(*p)++;
*out = buf_take(&b);
return true;
fail:
buf_free(&b);
return false;
}
static bool json_number(const char **p, double *out) {
json_ws(p);
char *end = NULL;
double v = strtod(*p, &end);
if (end == *p) return false;
*p = end;
*out = v;
return true;
}
static bool json_int(const char **p, int *out) {
double v = 0.0;
if (!json_number(p, &v)) return false;
if (v < 0) v = 0;
if (v > INT_MAX) v = INT_MAX;
*out = (int)v;
return true;
}
static bool json_bool(const char **p, bool *out) {
json_ws(p);
if (json_lit(p, "true")) {
*out = true;
return true;
}
if (json_lit(p, "false")) {
*out = false;
return true;
}
return false;
}
static bool json_skip_value(const char **p);
static bool json_skip_array(const char **p) {
json_ws(p);
if (**p != '[') return false;
(*p)++;
json_ws(p);
if (**p == ']') {
(*p)++;
return true;
}
for (;;) {
if (!json_skip_value(p)) return false;
json_ws(p);
if (**p == ']') {
(*p)++;
return true;
}
if (**p != ',') return false;
(*p)++;
}
}
static bool json_skip_object(const char **p) {
json_ws(p);
if (**p != '{') return false;
(*p)++;
json_ws(p);
if (**p == '}') {
(*p)++;
return true;
}
for (;;) {
char *key = NULL;
if (!json_string(p, &key)) return false;
free(key);
json_ws(p);
if (**p != ':') return false;
(*p)++;
if (!json_skip_value(p)) return false;
json_ws(p);
if (**p == '}') {
(*p)++;
return true;
}
if (**p != ',') return false;
(*p)++;
}
}
static bool json_skip_value(const char **p) {
json_ws(p);
if (**p == '"') {
char *s = NULL;
bool ok = json_string(p, &s);
free(s);
return ok;
}
if (**p == '{') return json_skip_object(p);
if (**p == '[') return json_skip_array(p);
if (json_lit(p, "true") || json_lit(p, "false") || json_lit(p, "null")) return true;
double v = 0.0;
return json_number(p, &v);
}
static bool json_raw_value(const char **p, char **out) {
json_ws(p);
const char *start = *p;
if (!json_skip_value(p)) return false;
size_t n = (size_t)(*p - start);
char *s = xmalloc(n + 1);
memcpy(s, start, n);
s[n] = '\0';
*out = s;
return true;
}
static char *json_minify_raw_value(const char *json) {
const char *p = json ? json : "null";
json_ws(&p);
const char *start = p;
if (!json_skip_value(&p)) return xstrdup(json ? json : "null");
const char *end = p;
buf b = {0};
bool in_string = false;
bool escape = false;
for (const char *s = start; s < end; s++) {
unsigned char c = (unsigned char)*s;
if (in_string) {
buf_putc(&b, (char)c);
if (escape) escape = false;
else if (c == '\\') escape = true;
else if (c == '"') in_string = false;
} else if (c == '"') {
in_string = true;
buf_putc(&b, (char)c);
} else if (!isspace(c)) {
buf_putc(&b, (char)c);
}
}
return buf_take(&b);
}
static bool json_content(const char **p, char **out) {
json_ws(p);
if (**p == '"') return json_string(p, out);
if (json_lit(p, "null")) {
*out = xstrdup("");
return true;
}
if (**p != '[') {
if (!json_skip_value(p)) return false;
*out = xstrdup("");
return true;
}
(*p)++;
buf b = {0};
json_ws(p);
while (**p && **p != ']') {
if (**p == '"') {
char *s = NULL;
if (!json_string(p, &s)) goto fail;
buf_puts(&b, s);
free(s);
} else if (**p == '{') {
(*p)++;
json_ws(p);
while (**p && **p != '}') {
char *key = NULL;
if (!json_string(p, &key)) goto fail;
json_ws(p);
if (**p != ':') {
free(key);
goto fail;
}
(*p)++;
if (!strcmp(key, "text")) {
char *s = NULL;
if (!json_string(p, &s)) {
free(key);
goto fail;
}
buf_puts(&b, s);
free(s);
} else if (!json_skip_value(p)) {
free(key);
goto fail;
}
free(key);
json_ws(p);
if (**p == ',') (*p)++;
json_ws(p);
}
if (**p != '}') goto fail;
(*p)++;
} else if (!json_skip_value(p)) {
goto fail;
}
json_ws(p);
if (**p == ',') (*p)++;
json_ws(p);
}
if (**p != ']') goto fail;
(*p)++;
*out = buf_take(&b);
return true;
fail:
buf_free(&b);
return false;
}
typedef enum {
REQ_CHAT,
REQ_COMPLETION,
} req_kind;
typedef enum {
API_OPENAI,
API_ANTHROPIC,
} api_style;
typedef struct {
char *id;
char *name;
char *arguments;
} tool_call;
typedef struct {
tool_call *v;
int len;
int cap;
} tool_calls;
typedef struct {
char *name;
char **prop;
int len;
int cap;
} tool_schema_order;
typedef struct {
tool_schema_order *v;
int len;
int cap;
} tool_schema_orders;
typedef struct {
char *role;
char *content;
char *reasoning;
char *tool_call_id;
tool_calls calls;
} chat_msg;
typedef struct {
chat_msg *v;
int len;
int cap;
} chat_msgs;
typedef struct {
char **v;
int len;
int cap;
size_t max_len;
} stop_list;
typedef struct {
req_kind kind;
api_style api;
ds4_tokens prompt;
char *model;
stop_list stops;
char *raw_body;
char *prompt_text;
tool_schema_orders tool_orders;
int max_tokens;
int top_k;
float temperature;
float top_p;
float min_p;
uint64_t seed;
bool stream;
bool stream_include_usage;
ds4_think_mode think_mode;
bool has_tools;
} request;
static void tool_call_free(tool_call *tc) {
free(tc->id);
free(tc->name);
free(tc->arguments);
memset(tc, 0, sizeof(*tc));
}
static void tool_calls_free(tool_calls *calls) {
for (int i = 0; i < calls->len; i++) tool_call_free(&calls->v[i]);
free(calls->v);
memset(calls, 0, sizeof(*calls));
}
static void tool_calls_push(tool_calls *calls, tool_call tc) {
if (calls->len == calls->cap) {
calls->cap = calls->cap ? calls->cap * 2 : 4;
calls->v = xrealloc(calls->v, (size_t)calls->cap * sizeof(calls->v[0]));
}
calls->v[calls->len++] = tc;
}
static void chat_msg_free(chat_msg *m) {
free(m->role);
free(m->content);
free(m->reasoning);
free(m->tool_call_id);
tool_calls_free(&m->calls);
memset(m, 0, sizeof(*m));
}
static void chat_msgs_free(chat_msgs *msgs) {
for (int i = 0; i < msgs->len; i++) chat_msg_free(&msgs->v[i]);
free(msgs->v);
memset(msgs, 0, sizeof(*msgs));
}
static void chat_msgs_push(chat_msgs *msgs, chat_msg msg) {
if (msgs->len == msgs->cap) {
msgs->cap = msgs->cap ? msgs->cap * 2 : 8;
msgs->v = xrealloc(msgs->v, (size_t)msgs->cap * sizeof(msgs->v[0]));
}
msgs->v[msgs->len++] = msg;
}
static void tool_schema_order_free(tool_schema_order *o) {
free(o->name);
for (int i = 0; i < o->len; i++) free(o->prop[i]);
free(o->prop);
memset(o, 0, sizeof(*o));
}
static void tool_schema_orders_free(tool_schema_orders *orders) {
for (int i = 0; i < orders->len; i++) tool_schema_order_free(&orders->v[i]);
free(orders->v);
memset(orders, 0, sizeof(*orders));
}
static void tool_schema_order_prop_push(tool_schema_order *o, char *prop) {
if (o->len == o->cap) {
o->cap = o->cap ? o->cap * 2 : 8;
o->prop = xrealloc(o->prop, (size_t)o->cap * sizeof(o->prop[0]));
}
o->prop[o->len++] = prop;
}
static int tool_schema_orders_find_index(const tool_schema_orders *orders, const char *name) {
if (!orders || !name) return -1;
for (int i = 0; i < orders->len; i++) {
if (orders->v[i].name && !strcmp(orders->v[i].name, name)) return i;
}
return -1;
}
static const tool_schema_order *tool_schema_orders_find(const tool_schema_orders *orders, const char *name) {
int idx = tool_schema_orders_find_index(orders, name);
return idx >= 0 ? &orders->v[idx] : NULL;
}
static void tool_schema_orders_push(tool_schema_orders *orders, tool_schema_order order) {
int idx = tool_schema_orders_find_index(orders, order.name);
if (idx >= 0) {
tool_schema_order_free(&orders->v[idx]);
orders->v[idx] = order;
return;
}
if (orders->len == orders->cap) {
orders->cap = orders->cap ? orders->cap * 2 : 8;
orders->v = xrealloc(orders->v, (size_t)orders->cap * sizeof(orders->v[0]));
}
orders->v[orders->len++] = order;
}
static void request_init(request *r, req_kind kind, int max_tokens) {
memset(r, 0, sizeof(*r));
r->kind = kind;
r->api = API_OPENAI;
r->model = xstrdup("deepseek-v4-flash");
r->max_tokens = max_tokens;
r->top_k = 0;
r->temperature = 1.0f;
r->top_p = 1.0f;
r->min_p = 0.0f;
r->think_mode = DS4_THINK_HIGH;
}
static void request_free(request *r) {
ds4_tokens_free(&r->prompt);
free(r->model);
for (int i = 0; i < r->stops.len; i++) free(r->stops.v[i]);
free(r->stops.v);
free(r->raw_body);
free(r->prompt_text);
tool_schema_orders_free(&r->tool_orders);
memset(r, 0, sizeof(*r));
}
static ds4_think_mode think_mode_from_enabled(bool enabled, ds4_think_mode effort) {
if (!enabled) return DS4_THINK_NONE;
return effort == DS4_THINK_MAX ? DS4_THINK_MAX : DS4_THINK_HIGH;
}
static bool parse_reasoning_effort_name(const char *s, ds4_think_mode *out) {
if (!s) return false;
if (!strcmp(s, "max")) {
*out = DS4_THINK_MAX;
return true;
}
if (!strcmp(s, "xhigh") || !strcmp(s, "high") ||
!strcmp(s, "medium") || !strcmp(s, "low"))
{
*out = DS4_THINK_HIGH;
return true;
}
return false;
}
static bool parse_reasoning_effort_value(const char **p, ds4_think_mode *out) {
json_ws(p);
if (json_lit(p, "null")) return true;
char *effort = NULL;
if (!json_string(p, &effort)) return false;
bool ok = parse_reasoning_effort_name(effort, out);
free(effort);
return ok;
}
static bool parse_thinking_control_value(const char **p, bool *thinking_enabled) {
json_ws(p);
if (json_lit(p, "null")) return true;
if (**p == 't' || **p == 'f') return json_bool(p, thinking_enabled);
if (**p != '{') return json_skip_value(p);
(*p)++;
json_ws(p);
while (**p && **p != '}') {
char *key = NULL;
if (!json_string(p, &key)) return false;
json_ws(p);
if (**p != ':') {
free(key);
return false;
}
(*p)++;
if (!strcmp(key, "type")) {
char *type = NULL;
if (!json_string(p, &type)) {
free(key);
return false;
}
if (!strcmp(type, "enabled")) *thinking_enabled = true;
else if (!strcmp(type, "disabled")) *thinking_enabled = false;
free(type);
} else if (!json_skip_value(p)) {
free(key);
return false;
}
free(key);
json_ws(p);
if (**p == ',') (*p)++;
json_ws(p);
}
if (**p != '}') return false;
(*p)++;
return true;
}
static bool parse_output_config_effort(const char **p, ds4_think_mode *effort) {
json_ws(p);
if (json_lit(p, "null")) return true;
if (**p != '{') return json_skip_value(p);
(*p)++;
json_ws(p);
while (**p && **p != '}') {
char *key = NULL;
if (!json_string(p, &key)) return false;
json_ws(p);
if (**p != ':') {
free(key);
return false;
}
(*p)++;
if (!strcmp(key, "effort")) {
if (!parse_reasoning_effort_value(p, effort)) {
free(key);
return false;
}
} else if (!json_skip_value(p)) {
free(key);
return false;
}
free(key);
json_ws(p);
if (**p == ',') (*p)++;
json_ws(p);
}
if (**p != '}') return false;
(*p)++;
return true;
}
static bool model_alias_disables_thinking(const char *model) {
return model && !strcmp(model, "deepseek-chat");
}
static bool model_alias_enables_thinking(const char *model) {
return model && !strcmp(model, "deepseek-reasoner");
}
static void stop_list_clear(stop_list *stops) {
for (int i = 0; i < stops->len; i++) free(stops->v[i]);
stops->len = 0;
stops->max_len = 0;
}
static void stop_list_push(stop_list *stops, char *s) {
if (!s || !s[0]) {
free(s);
return;
}
if (stops->len == stops->cap) {
stops->cap = stops->cap ? stops->cap * 2 : 4;
stops->v = xrealloc(stops->v, (size_t)stops->cap * sizeof(stops->v[0]));
}
size_t n = strlen(s);
if (n > stops->max_len) stops->max_len = n;
stops->v[stops->len++] = s;
}
static bool parse_stop(const char **p, stop_list *out) {
json_ws(p);
stop_list_clear(out);
if (**p == '"') {
char *s = NULL;
if (!json_string(p, &s)) return false;
stop_list_push(out, s);
return true;
}
if (**p != '[') return json_skip_value(p);
(*p)++;
json_ws(p);
while (**p && **p != ']') {
if (**p == '"') {
char *s = NULL;
if (!json_string(p, &s)) return false;
stop_list_push(out, s);
} else if (!json_skip_value(p)) {
return false;
}
json_ws(p);
if (**p == ',') (*p)++;
json_ws(p);
}
if (**p != ']') return false;
(*p)++;
return true;
}
static bool stop_list_find_from(const stop_list *stops, const char *text,
size_t from, size_t *pos, size_t *len) {
if (!stops->len || !text) return false;
bool found = false;
size_t best_pos = 0, best_len = 0;
for (int i = 0; i < stops->len; i++) {
char *p = strstr(text + from, stops->v[i]);
if (!p) continue;
size_t ppos = (size_t)(p - text);
size_t plen = strlen(stops->v[i]);
if (!found || ppos < best_pos) {
found = true;
best_pos = ppos;
best_len = plen;
}
}
if (!found) return false;
*pos = best_pos;
*len = best_len;
return true;
}
static size_t stop_list_stream_safe_len(const stop_list *stops, size_t text_len) {
/* Streaming cannot emit the last max_stop_len-1 bytes yet: a stop sequence
* may start there and finish in the next token. The final flush releases
* this small tail once generation ends without a stop hit. */
if (!stops->len || stops->max_len <= 1) return text_len;
const size_t hold = stops->max_len - 1;
return text_len > hold ? text_len - hold : 0;
}
static int utf8_expected_len(unsigned char c) {
if (c < 0x80) return 1;
if (c >= 0xc2 && c <= 0xdf) return 2;
if (c >= 0xe0 && c <= 0xef) return 3;
if (c >= 0xf0 && c <= 0xf4) return 4;
return 1;
}
/* Tokenizers can split a multi-byte UTF-8 character across two tokens. If an
* SSE delta ends at that boundary, some clients replace the incomplete byte
* sequence with U+FFFD and later send the corrupted text back, destroying KV
* cache prefix matches. Hold only the trailing incomplete character; the next
* generated token will complete it. */
static size_t utf8_stream_safe_len(const char *s, size_t start,
size_t limit, bool final) {
if (final || !s || limit <= start) return limit;
size_t p = limit;
int cont = 0;
while (p > start && cont < 4 &&
(((unsigned char)s[p - 1] & 0xc0) == 0x80))
{
p--;
cont++;
}
if (p == limit) {
return utf8_expected_len((unsigned char)s[limit - 1]) > 1 ?
limit - 1 : limit;
}
if (p == start && (((unsigned char)s[p] & 0xc0) == 0x80)) return start;
size_t lead = p - 1;
int need = utf8_expected_len((unsigned char)s[lead]);
return (limit - lead) < (size_t)need ? lead : limit;
}
static bool parse_stream_options(const char **p, bool *include_usage) {
json_ws(p);
if (**p != '{') return json_skip_value(p);
(*p)++;
json_ws(p);
while (**p && **p != '}') {
char *key = NULL;
if (!json_string(p, &key)) return false;
json_ws(p);
if (**p != ':') {
free(key);
return false;
}
(*p)++;
if (!strcmp(key, "include_usage")) {
if (!json_bool(p, include_usage)) {
free(key);
return false;
}
} else if (!json_skip_value(p)) {
free(key);
return false;
}
free(key);
json_ws(p);
if (**p == ',') (*p)++;
json_ws(p);
}
if (**p != '}') return false;
(*p)++;
return true;
}
static bool parse_function_call(const char **p, tool_call *tc) {
json_ws(p);
if (**p != '{') return false;
(*p)++;
json_ws(p);
while (**p && **p != '}') {
char *key = NULL;
if (!json_string(p, &key)) goto bad;
json_ws(p);
if (**p != ':') {
free(key);
goto bad;
}
(*p)++;
if (!strcmp(key, "name")) {
free(tc->name);
if (!json_string(p, &tc->name)) {
free(key);
goto bad;
}
} else if (!strcmp(key, "arguments")) {
free(tc->arguments);
json_ws(p);
if (**p == '"') {
if (!json_string(p, &tc->arguments)) {
free(key);
goto bad;
}
} else if (!json_raw_value(p, &tc->arguments)) {
free(key);
goto bad;
}
} else if (!json_skip_value(p)) {
free(key);
goto bad;
}
free(key);
json_ws(p);
if (**p == ',') (*p)++;
json_ws(p);
}
if (**p != '}') goto bad;
(*p)++;
return true;
bad:
return false;
}
static bool parse_tool_calls_value(const char **p, tool_calls *calls) {
json_ws(p);
if (json_lit(p, "null")) return true;
if (**p != '[') return false;
(*p)++;
json_ws(p);
while (**p && **p != ']') {
if (**p != '{') return false;
(*p)++;
tool_call tc = {0};
json_ws(p);
while (**p && **p != '}') {
char *key = NULL;
if (!json_string(p, &key)) goto bad;
json_ws(p);
if (**p != ':') {
free(key);
goto bad;
}
(*p)++;
if (!strcmp(key, "id")) {
free(tc.id);
if (!json_string(p, &tc.id)) {
free(key);
goto bad;
}
} else if (!strcmp(key, "function")) {
if (!parse_function_call(p, &tc)) {
free(key);
goto bad;
}
} else if (!json_skip_value(p)) {
free(key);
goto bad;
}
free(key);
json_ws(p);
if (**p == ',') (*p)++;
json_ws(p);
}
if (**p != '}') goto bad;
(*p)++;
if (tc.name && tc.arguments) {
tool_calls_push(calls, tc);
memset(&tc, 0, sizeof(tc));
}
tool_call_free(&tc);
json_ws(p);
if (**p == ',') (*p)++;
json_ws(p);
continue;
bad:
tool_call_free(&tc);
return false;
}
if (**p != ']') return false;
(*p)++;
return true;
}