forked from antirez/ds4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathds4_agent.c
More file actions
10244 lines (9461 loc) · 384 KB
/
Copy pathds4_agent.c
File metadata and controls
10244 lines (9461 loc) · 384 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"
#include "ds4_distributed.h"
#include "ds4_help.h"
#include "ds4_kvstore.h"
#include "ds4_web.h"
#include "linenoise.h"
#include <errno.h>
#include <ctype.h>
#include <dirent.h>
#include <fnmatch.h>
#include <fcntl.h>
#include <limits.h>
#include <math.h>
#include <poll.h>
#include <pthread.h>
#include <regex.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
/* This is intentionally not in linenoise.h, but it is part of the existing
* multiplexed editor implementation. The agent uses it only to restore text
* after Enter is pressed while the model is still busy. */
int linenoiseEditInsert(struct linenoiseState *l, const char *c, size_t clen);
static int set_nonblock(int fd, bool on, int *old_flags);
static bool agent_parse_bool_default(const char *s, bool def);
/* ============================================================================
* Configuration, Worker State, And Streaming Types
* ============================================================================
*
* The agent is intentionally a single process: the UI thread owns terminal
* input/output, while the worker thread owns the live DS4 session and KV state.
* These types define the shared state and the small streaming state machines
* used to render sampled assistant text and DSML tool calls as they arrive.
*/
typedef struct {
const char *prompt;
const char *system;
const char *trace_path;
int n_predict;
int ctx_size;
float temperature;
float top_p;
float min_p;
uint64_t seed;
ds4_think_mode think_mode;
} agent_generation_options;
typedef struct {
ds4_engine_options engine;
agent_generation_options gen;
const char *chdir_path;
bool non_interactive;
} agent_config;
typedef enum {
AGENT_WORKER_IDLE,
AGENT_WORKER_PREFILL,
AGENT_WORKER_GENERATING,
AGENT_WORKER_COMPACTING,
AGENT_WORKER_DRAINING,
AGENT_WORKER_SAVING,
AGENT_WORKER_ERROR,
AGENT_WORKER_STOPPED,
} agent_worker_state;
typedef struct {
agent_worker_state state;
int prefill_done;
int prefill_total;
unsigned prefill_label;
double prefill_tps;
int generated;
double gen_tps;
bool greedy_sampling;
int ctx_used;
int ctx_size;
int power_percent;
char error[256];
} agent_status;
typedef struct agent_bash_job agent_bash_job;
typedef struct {
ds4_engine *engine;
agent_config *cfg;
ds4_session *session;
ds4_tokens transcript;
char *cache_dir;
char *sysprompt_path;
char session_sha[41];
char *session_title;
uint64_t session_created_at;
char *legacy_session_path_to_delete;
bool user_activity;
bool session_dirty;
pthread_t thread;
pthread_mutex_t mu;
pthread_cond_t cond;
int wake_fd[2];
FILE *trace;
bool wake_pending;
bool stop;
bool interrupt;
bool initialized;
bool save_requested;
bool compact_requested;
bool power_requested;
int requested_power;
int progress_base;
double progress_started_at;
int last_system_prompt_reminder_at;
char *cmd_text;
agent_status status;
char *out;
size_t out_len;
size_t out_cap;
ds4_web *web;
bool web_approval_pending;
bool web_approval_answered;
bool web_approval_result;
char web_approval_message[256];
char web_approval_error[160];
bool queued_user_drain_pending;
bool queued_user_drain_answered;
char *queued_user_drain_text;
bool datetime_context_injected;
char more_path[PATH_MAX];
int more_next_line;
bool more_bare;
bool more_valid;
agent_bash_job *bash_jobs;
int next_bash_job_id;
bool raw_mode_needs_restore;
} agent_worker;
static unsigned agent_next_prefill_label(void);
typedef struct agent_tail_capture {
char *buf;
size_t cap;
size_t start;
size_t len;
size_t total;
} agent_tail_capture;
typedef enum {
AGENT_MD_PENDING_NONE,
AGENT_MD_PENDING_STAR,
AGENT_MD_PENDING_BACKTICK,
} agent_markdown_pending;
typedef struct agent_syntax agent_syntax;
typedef struct {
ds4_engine *engine;
agent_worker *worker;
bool format_thinking;
bool format_markdown;
bool in_think;
bool color_open;
bool use_color;
bool last_output_newline;
bool wrote_visible_output;
bool md_bold;
bool md_italic;
bool md_inline_code;
bool md_code_block;
bool md_fence_info;
bool md_code_line_start;
bool md_code_in_ml_comment;
bool md_syntax_silent;
bool md_syntax_has_highlight;
agent_markdown_pending md_pending;
size_t md_pending_len;
const agent_syntax *md_syntax;
char md_fence_lang[32];
size_t md_fence_lang_len;
const char *md_code_line_prefix;
const char *md_code_line_prefix_color;
bool md_code_highlight_upto;
char *md_code_line;
size_t md_code_line_len;
size_t md_code_line_cap;
char pending[16];
size_t pending_len;
char utf8_pending[4];
size_t utf8_pending_len;
size_t utf8_pending_need;
agent_tail_capture *capture;
} agent_token_renderer;
typedef struct {
char *name;
char *value;
bool is_string;
} agent_tool_arg;
typedef struct {
char *name;
agent_tool_arg *args;
int argc;
int argcap;
} agent_tool_call;
typedef struct {
agent_tool_call *v;
int len;
int cap;
} agent_tool_calls;
typedef enum {
AGENT_DSML_SEARCH,
AGENT_DSML_STRUCTURAL,
AGENT_DSML_PARAM_VALUE,
AGENT_DSML_DONE,
AGENT_DSML_ERROR,
} agent_dsml_state;
typedef struct {
agent_dsml_state state;
char search_tail[64];
size_t search_len;
char *raw;
size_t raw_len;
size_t raw_cap;
size_t parse_pos;
agent_tool_call current;
char *param_name;
bool param_is_string;
size_t param_value_start;
bool param_close_prefix;
agent_tool_calls calls;
char error[160];
} agent_dsml_parser;
typedef enum {
AGENT_TOOL_PARAM_NORMAL,
AGENT_TOOL_PARAM_PATH,
AGENT_TOOL_PARAM_OFFSET,
AGENT_TOOL_PARAM_CONTENT,
AGENT_TOOL_PARAM_DIFF_OLD,
AGENT_TOOL_PARAM_DIFF_NEW,
AGENT_TOOL_PARAM_BASH_COMMAND,
} agent_tool_param_kind;
typedef struct {
bool active;
bool tool_announced;
bool param_active;
bool at_line_start;
bool last_output_newline;
agent_tool_param_kind param_kind;
char tool_name[64];
char param_name[64];
char param_end_tail[64];
size_t param_end_len;
bool read_style;
bool read_prefix_rendered;
bool read_line_rendered;
char read_path[512];
char read_start[32];
char read_max[32];
char read_whole[8];
char tool_path[512];
bool code_param_active;
} agent_tool_visualizer;
typedef struct {
char tail[32];
size_t len;
} agent_dsml_marker_detector;
typedef struct {
agent_token_renderer *renderer;
agent_dsml_parser *parser;
agent_tool_visualizer viz;
bool in_think;
bool dsml_active;
bool dsml_ignored;
bool replay;
char pending[16];
size_t pending_len;
char dsml_start_tail[64];
size_t dsml_start_len;
agent_dsml_marker_detector plain_dsml;
agent_dsml_marker_detector think_dsml;
bool dsml_in_think;
bool dsml_in_think_reported;
bool post_think_gap;
bool tool_preflight_error;
char tool_preflight_error_msg[256];
} agent_stream_renderer;
typedef struct {
bool active;
bool done;
} agent_edit_upto_forcer;
static volatile sig_atomic_t agent_sigint;
static agent_worker *agent_completion_worker;
static void worker_apply_pending_power(agent_worker *w);
static void agent_trace(agent_worker *w, const char *fmt, ...);
static void agent_trace_text(agent_worker *w, const char *label,
const char *text, size_t len);
static void agent_publish_system_status(agent_worker *w, const char *msg);
static int agent_web_confirm(void *privdata, const char *message,
char *err, size_t err_len);
static void agent_web_log(void *privdata, const char *message);
static bool agent_preflight_edit_old(agent_worker *w, const agent_tool_call *call,
char *err, size_t err_len);
static int agent_worker_sync_tokens(agent_worker *w, const ds4_tokens *tokens,
bool publish_progress,
char *err, size_t err_len);
/* ============================================================================
* Small Utilities And Command-Line Parsing
* ============================================================================
*/
static void agent_sigint_handler(int sig) {
(void)sig;
agent_sigint = 1;
}
static void *xmalloc(size_t n) {
void *p = malloc(n ? n : 1);
if (!p) {
perror("ds4-agent: malloc");
exit(1);
}
return p;
}
static char *xstrdup(const char *s) {
if (!s) 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 *xrealloc(void *ptr, size_t n) {
void *p = realloc(ptr, n ? n : 1);
if (!p) {
perror("ds4-agent: realloc");
exit(1);
}
return p;
}
static void write_all(int fd, const char *p, size_t n) {
while (n) {
ssize_t wr = write(fd, p, n);
if (wr < 0) {
if (errno == EINTR) continue;
return;
}
p += wr;
n -= (size_t)wr;
}
}
typedef struct {
char *ptr;
size_t len;
size_t cap;
} agent_input_buf;
static void agent_input_buf_append(agent_input_buf *b, const char *s, size_t n) {
if (!n) return;
if (b->len + n + 1 > b->cap) {
size_t cap = b->cap ? b->cap * 2 : 4096;
while (cap < b->len + n + 1) cap *= 2;
b->ptr = xrealloc(b->ptr, cap);
b->cap = cap;
}
memcpy(b->ptr + b->len, s, n);
b->len += n;
b->ptr[b->len] = '\0';
}
static char *agent_input_buf_take(agent_input_buf *b) {
if (!b->ptr) return xstrdup("");
char *p = b->ptr;
memset(b, 0, sizeof(*b));
return p;
}
static void agent_input_buf_free(agent_input_buf *b) {
free(b->ptr);
memset(b, 0, sizeof(*b));
}
static int parse_int(const char *s, const char *opt) {
char *end = NULL;
long v = strtol(s, &end, 10);
if (s[0] == '\0' || *end != '\0' || v <= 0 || v > INT32_MAX) {
fprintf(stderr, "ds4-agent: invalid value for %s: %s\n", opt, s);
exit(2);
}
return (int)v;
}
static bool parse_power_percent(const char *arg, int *out) {
char *end = NULL;
long v = strtol(arg, &end, 10);
if (!arg[0] || *end != '\0' || v < 1 || v > 100) return false;
*out = (int)v;
return true;
}
static bool agent_slash_command_with_args(const char *cmd, const char *name) {
size_t len = strlen(name);
return !strncmp(cmd, name, len) &&
(cmd[len] == '\0' || isspace((unsigned char)cmd[len]));
}
static bool agent_slash_command_known(const char *cmd) {
return !strcmp(cmd, "/help") ||
!strcmp(cmd, "/save") ||
!strcmp(cmd, "/compact") ||
!strcmp(cmd, "/list") ||
!strcmp(cmd, "/quit") ||
!strcmp(cmd, "/exit") ||
!strcmp(cmd, "/new") ||
agent_slash_command_with_args(cmd, "/power") ||
agent_slash_command_with_args(cmd, "/switch") ||
agent_slash_command_with_args(cmd, "/del") ||
agent_slash_command_with_args(cmd, "/strip") ||
agent_slash_command_with_args(cmd, "/history");
}
static uint64_t parse_u64(const char *s, const char *opt) {
char *end = NULL;
unsigned long long v = strtoull(s, &end, 10);
if (s[0] == '\0' || *end != '\0' || v == 0) {
fprintf(stderr, "ds4-agent: invalid value for %s: %s\n", opt, s);
exit(2);
}
return (uint64_t)v;
}
static float parse_float_range(const char *s, const char *opt, float min, float max) {
char *end = NULL;
float v = strtof(s, &end);
if (s[0] == '\0' || *end != '\0' || !isfinite(v) || v < min || v > max) {
fprintf(stderr, "ds4-agent: invalid value for %s: %s\n", opt, s);
exit(2);
}
return v;
}
static ds4_backend parse_backend(const char *s) {
if (!strcmp(s, "metal")) return DS4_BACKEND_METAL;
if (!strcmp(s, "cuda")) return DS4_BACKEND_CUDA;
if (!strcmp(s, "cpu")) return DS4_BACKEND_CPU;
fprintf(stderr, "ds4-agent: invalid backend: %s\n", s);
exit(2);
}
static ds4_backend default_backend(void) {
#ifdef DS4_NO_GPU
return DS4_BACKEND_CPU;
#elif defined(__APPLE__)
return DS4_BACKEND_METAL;
#else
return DS4_BACKEND_CUDA;
#endif
}
static double now_sec(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (double)ts.tv_sec + (double)ts.tv_nsec * 1.0e-9;
}
static void usage(FILE *fp, const char *topic) {
ds4_help_print(fp, DS4_HELP_AGENT, topic);
}
static const char *need_arg(int *i, int argc, char **argv, const char *opt) {
if (*i + 1 >= argc) {
fprintf(stderr, "ds4-agent: missing value for %s\n", opt);
exit(2);
}
return argv[++(*i)];
}
static agent_config parse_options(int argc, char **argv) {
agent_config c = {
.engine = {
.model_path = "ds4flash.gguf",
.backend = default_backend(),
.mtp_draft_tokens = 1,
.mtp_margin = 3.0f,
},
.gen = {
.system = "You are a helpful coding assistant running inside ds4-agent.",
.n_predict = 50000,
.ctx_size = 100000,
.temperature = DS4_DEFAULT_TEMPERATURE,
.top_p = DS4_DEFAULT_TOP_P,
.min_p = DS4_DEFAULT_MIN_P,
.think_mode = DS4_THINK_HIGH,
},
};
bool steering_scale_set = false;
for (int i = 1; i < argc; i++) {
const char *arg = argv[i];
if (!strcmp(arg, "-h") || !strcmp(arg, "--help")) {
const char *topic = (i + 1 < argc && argv[i + 1][0] != '-') ?
argv[i + 1] : NULL;
usage(stdout, topic);
exit(0);
}
char dist_parse_err[256] = {0};
ds4_dist_cli_parse_result dist_parse =
ds4_dist_parse_cli_arg(arg,
&i,
argc,
argv,
&c.engine.distributed,
dist_parse_err,
sizeof(dist_parse_err));
if (dist_parse == DS4_DIST_CLI_ERROR) {
fprintf(stderr,
"ds4-agent: %s\n",
dist_parse_err[0] ? dist_parse_err : "invalid distributed option");
exit(2);
}
if (dist_parse == DS4_DIST_CLI_MATCHED) continue;
if (!strcmp(arg, "-p") || !strcmp(arg, "--prompt")) {
c.gen.prompt = need_arg(&i, argc, argv, arg);
} else if (!strcmp(arg, "--non-interactive")) {
c.non_interactive = true;
} else if (!strcmp(arg, "-sys") || !strcmp(arg, "--system")) {
c.gen.system = need_arg(&i, argc, argv, arg);
} else if (!strcmp(arg, "--trace")) {
c.gen.trace_path = need_arg(&i, argc, argv, arg);
} else if (!strcmp(arg, "-m") || !strcmp(arg, "--model")) {
c.engine.model_path = need_arg(&i, argc, argv, arg);
} else if (!strcmp(arg, "--mtp")) {
c.engine.mtp_path = need_arg(&i, argc, argv, arg);
} else if (!strcmp(arg, "--mtp-draft")) {
c.engine.mtp_draft_tokens = parse_int(need_arg(&i, argc, argv, arg), arg);
} else if (!strcmp(arg, "--mtp-margin")) {
c.engine.mtp_margin = parse_float_range(need_arg(&i, argc, argv, arg), arg, 0.0f, 1000.0f);
} else if (!strcmp(arg, "-c") || !strcmp(arg, "--ctx")) {
c.gen.ctx_size = parse_int(need_arg(&i, argc, argv, arg), arg);
} else if (!strcmp(arg, "-n") || !strcmp(arg, "--tokens")) {
c.gen.n_predict = parse_int(need_arg(&i, argc, argv, arg), arg);
} else if (!strcmp(arg, "--temp")) {
c.gen.temperature = parse_float_range(need_arg(&i, argc, argv, arg), arg, 0.0f, 100.0f);
} else if (!strcmp(arg, "--top-p")) {
c.gen.top_p = parse_float_range(need_arg(&i, argc, argv, arg), arg, 0.0f, 1.0f);
} else if (!strcmp(arg, "--min-p")) {
c.gen.min_p = parse_float_range(need_arg(&i, argc, argv, arg), arg, 0.0f, 1.0f);
} else if (!strcmp(arg, "--seed")) {
c.gen.seed = parse_u64(need_arg(&i, argc, argv, arg), arg);
} else if (!strcmp(arg, "--think")) {
c.gen.think_mode = DS4_THINK_HIGH;
} else if (!strcmp(arg, "--think-max")) {
c.gen.think_mode = DS4_THINK_MAX;
} else if (!strcmp(arg, "--nothink")) {
c.gen.think_mode = DS4_THINK_NONE;
} else if (!strcmp(arg, "--backend")) {
c.engine.backend = parse_backend(need_arg(&i, argc, argv, arg));
} else if (!strcmp(arg, "--metal")) {
c.engine.backend = DS4_BACKEND_METAL;
} else if (!strcmp(arg, "--cuda")) {
c.engine.backend = DS4_BACKEND_CUDA;
} else if (!strcmp(arg, "--cpu")) {
c.engine.backend = DS4_BACKEND_CPU;
} else if (!strcmp(arg, "-t") || !strcmp(arg, "--threads")) {
c.engine.n_threads = parse_int(need_arg(&i, argc, argv, arg), arg);
} else if (!strcmp(arg, "--chdir")) {
c.chdir_path = need_arg(&i, argc, argv, arg);
} else if (!strcmp(arg, "--quality")) {
c.engine.quality = true;
} else if (!strcmp(arg, "--ssd-streaming")) {
c.engine.ssd_streaming = true;
} else if (!strcmp(arg, "--ssd-streaming-cold")) {
c.engine.ssd_streaming_cold = true;
} else if (!strcmp(arg, "--ssd-streaming-cache-experts")) {
uint32_t experts = 0;
uint64_t bytes = 0;
if (!ds4_parse_streaming_cache_experts_arg(
need_arg(&i, argc, argv, arg), &experts, &bytes)) {
fprintf(stderr,
"ds4-agent: --ssd-streaming-cache-experts must be a positive count or <number>GB\n");
exit(2);
}
c.engine.ssd_streaming_cache_experts = experts;
c.engine.ssd_streaming_cache_bytes = bytes;
} else if (!strcmp(arg, "--ssd-streaming-preload-experts")) {
int v = parse_int(need_arg(&i, argc, argv, arg), arg);
if (v <= 0) {
fprintf(stderr, "ds4-agent: --ssd-streaming-preload-experts must be positive\n");
exit(2);
}
c.engine.ssd_streaming_preload_experts = (uint32_t)v;
} else if (!strcmp(arg, "--simulate-used-memory")) {
if (!ds4_parse_gib_arg(need_arg(&i, argc, argv, arg),
&c.engine.simulate_used_memory_bytes)) {
fprintf(stderr,
"ds4-agent: --simulate-used-memory must be a positive GiB value, e.g. 64GB\n");
exit(2);
}
} else if (!strcmp(arg, "--prefill-chunk")) {
int v = parse_int(need_arg(&i, argc, argv, arg), arg);
if (v <= 0) {
fprintf(stderr, "ds4-agent: --prefill-chunk must be positive\n");
exit(2);
}
c.engine.prefill_chunk = (uint32_t)v;
} else if (!strcmp(arg, "--power")) {
c.engine.power_percent = parse_int(need_arg(&i, argc, argv, arg), arg);
if (c.engine.power_percent < 1 || c.engine.power_percent > 100) {
fprintf(stderr, "ds4-agent: --power must be between 1 and 100\n");
exit(2);
}
} else if (!strcmp(arg, "--warm-weights")) {
c.engine.warm_weights = true;
} else if (!strcmp(arg, "--dir-steering-file")) {
c.engine.directional_steering_file = need_arg(&i, argc, argv, arg);
} else if (!strcmp(arg, "--dir-steering-ffn")) {
c.engine.directional_steering_ffn = parse_float_range(need_arg(&i, argc, argv, arg), arg, -100.0f, 100.0f);
steering_scale_set = true;
} else if (!strcmp(arg, "--dir-steering-attn")) {
c.engine.directional_steering_attn = parse_float_range(need_arg(&i, argc, argv, arg), arg, -100.0f, 100.0f);
steering_scale_set = true;
} else {
fprintf(stderr, "ds4-agent: unknown option: %s\n", arg);
usage(stderr, NULL);
exit(2);
}
}
if (c.engine.directional_steering_file && !steering_scale_set)
c.engine.directional_steering_ffn = 1.0f;
char dist_err[256];
if (ds4_dist_prepare_engine_options(&c.engine.distributed,
&c.engine,
dist_err,
sizeof(dist_err)) != 0) {
fprintf(stderr, "ds4-agent: %s\n", dist_err);
exit(2);
}
if (c.engine.distributed.role == DS4_DISTRIBUTED_WORKER) {
fprintf(stderr, "ds4-agent: --role worker is a serving mode; start workers with ./ds4\n");
exit(2);
}
return c;
}
static void log_context_memory(ds4_backend backend,
int ctx_size,
uint32_t prefill_chunk) {
ds4_context_memory m =
ds4_context_memory_estimate_with_prefill(backend,
ctx_size,
prefill_chunk);
fprintf(stderr,
"ds4-agent: context buffers %.2f MiB (ctx=%d, backend=%s, prefill_chunk=%u, raw_kv_rows=%u, compressed_kv_rows=%u)\n",
(double)m.total_bytes / (1024.0 * 1024.0),
ctx_size,
ds4_backend_name(backend),
m.prefill_cap,
m.raw_cap,
m.comp_cap);
}
static ds4_think_mode effective_think_mode(const agent_config *cfg) {
return ds4_think_mode_for_context(cfg->gen.think_mode, cfg->gen.ctx_size);
}
/* ============================================================================
* System Prompt Rendering And Worker Output Queues
* ============================================================================
*/
static const char agent_tools_prompt_intro[] =
"You are a coding agent running in a local workspace. Use tools for local file and system work. "
"Avoid printing large file contents or large code blocks as answers; create or edit files with tools, "
"then summarize results briefly.\n\n"
"## Tools\n\n"
"You have access to native DSML tools. Invoke tools by writing exactly this shape:\n\n"
"<|DSML|tool_calls>\n"
"<|DSML|invoke name=\"$TOOL_NAME\">\n"
"<|DSML|parameter name=\"$PARAMETER_NAME\" string=\"true|false\">$PARAMETER_VALUE</|DSML|parameter>\n"
"</|DSML|invoke>\n"
"</|DSML|tool_calls>\n\n"
"Tool calls are not allowed inside <think></think>; finish thinking before emitting DSML.\n\n"
"String parameters use raw text and string=\"true\". Numbers and booleans use JSON text and string=\"false\".\n\n"
"Read defaults to a bounded chunk: path alone returns the first 500 lines, not the whole file. "
"If read says more lines are available, call more with count=<lines> to read the next chunk; "
"more defaults to the next 500 lines. "
"The read result also reports continue_offset=N, which is the next start_line if you need to jump manually. "
"If the user explicitly asks you to read a complete file into context, call read with whole=true. "
"A whole-file read may fail if the result would not fit the current context; then explain that and use chunks.\n\n";
static const char agent_tools_prompt_edit_line[] =
"## Editing files\n\n"
"Use write for new files or deliberate whole-file replacement. Use edit with path, old, and new for changes. "
"For edit, always put the edited file path as the first parameter. "
"The old text must match exactly once in the current file; otherwise edit fails for safety.\n"
"For large replacements, prefer anchored old text: write the first lines, then [upto], then the final lines. "
"The tool replaces everything from the head through the tail. If the head or tail is ambiguous, the edit fails.\n"
"After [upto], always write unique final lines before closing old; never close old immediately after [upto].\n"
"Do not use a generic tail anchor like:\n"
"- BigNum bignum_add(BigNum *a, BigNum *b) {\n"
"- [upto]\n"
"- }\n"
"because the closing brace may match many functions. Instead include final lines that are unique near that function, "
"for example its last calculation and return line before the brace.\n"
"Example anchored edit:\n"
"<|DSML|tool_calls>\n"
"<|DSML|invoke name=\"edit\">\n"
"<|DSML|parameter name=\"path\" string=\"true\">/tmp/example.c</|DSML|parameter>\n"
"<|DSML|parameter name=\"old\" string=\"true\">static int parse(void) {\n"
" int ok = 0;\n"
"[upto]\n"
" return ok;\n"
"}</|DSML|parameter>\n"
"<|DSML|parameter name=\"new\" string=\"true\">static int parse(void) {\n"
" return parse_impl();\n"
"}</|DSML|parameter>\n"
"</|DSML|invoke>\n"
"</|DSML|tool_calls>\n"
"To insert text, use edit with old set to an exact unique anchor and new set to that anchor plus the added text.\n"
"Use read raw=true only when you need plain file text without line numbers or read annotations.\n\n";
static const char agent_tools_prompt_after_edit[] =
"For long-running bash commands, pass refresh_sec. If a bash job is still running, use "
"bash_status to check it early or bash_stop to terminate it.\n\n"
"Use google_search to find web pages. Use visit_page to read a known URL with a visible browser. "
"The first web call may ask the user for permission to start Chrome.\n\n"
"### Available Tool Schemas\n\n"
"{\n"
" \"type\": \"function\",\n"
" \"function\": {\n"
" \"name\": \"google_search\",\n"
" \"description\": \"Search Google in a visible browser and return compact Markdown links.\",\n"
" \"parameters\": {\n"
" \"type\": \"object\",\n"
" \"properties\": {\n"
" \"query\": {\"type\": \"string\"}\n"
" },\n"
" \"required\": [\"query\"]\n"
" }\n"
" }\n"
"}\n\n"
"{\n"
" \"type\": \"function\",\n"
" \"function\": {\n"
" \"name\": \"visit_page\",\n"
" \"description\": \"Open a URL in a visible browser and return rendered page Markdown.\",\n"
" \"parameters\": {\n"
" \"type\": \"object\",\n"
" \"properties\": {\n"
" \"url\": {\"type\": \"string\"}\n"
" },\n"
" \"required\": [\"url\"]\n"
" }\n"
" }\n"
"}\n\n"
"{\n"
" \"type\": \"function\",\n"
" \"function\": {\n"
" \"name\": \"bash\",\n"
" \"description\": \"Run a shell command.\",\n"
" \"parameters\": {\n"
" \"type\": \"object\",\n"
" \"properties\": {\n"
" \"command\": {\"type\": \"string\"},\n"
" \"timeout_sec\": {\"type\": \"number\"},\n"
" \"refresh_sec\": {\"type\": \"number\"}\n"
" },\n"
" \"required\": [\"command\"]\n"
" }\n"
" }\n"
"}\n\n"
"{\n"
" \"type\": \"function\",\n"
" \"function\": {\n"
" \"name\": \"bash_status\",\n"
" \"description\": \"Report current status and new output for a bash job.\",\n"
" \"parameters\": {\n"
" \"type\": \"object\",\n"
" \"properties\": {\n"
" \"job\": {\"type\": \"number\"},\n"
" \"pid\": {\"type\": \"number\"},\n"
" \"refresh_sec\": {\"type\": \"number\"}\n"
" },\n"
" \"required\": [\"job\"]\n"
" }\n"
" }\n"
"}\n\n"
"{\n"
" \"type\": \"function\",\n"
" \"function\": {\n"
" \"name\": \"bash_stop\",\n"
" \"description\": \"Terminate a running bash job and report its final output.\",\n"
" \"parameters\": {\n"
" \"type\": \"object\",\n"
" \"properties\": {\n"
" \"job\": {\"type\": \"number\"},\n"
" \"pid\": {\"type\": \"number\"},\n"
" \"refresh_sec\": {\"type\": \"number\"}\n"
" },\n"
" \"required\": [\"job\"]\n"
" }\n"
" }\n"
"}\n\n"
"{\n"
" \"type\": \"function\",\n"
" \"function\": {\n"
" \"name\": \"read\",\n"
" \"description\": \"Read a text file or a range of lines.\",\n"
" \"parameters\": {\n"
" \"type\": \"object\",\n"
" \"properties\": {\n"
" \"path\": {\"type\": \"string\"},\n"
" \"start_line\": {\"type\": \"number\"},\n"
" \"max_lines\": {\"type\": \"number\"},\n"
" \"whole\": {\"type\": \"boolean\"},\n"
" \"raw\": {\"type\": \"boolean\"}\n"
" },\n"
" \"required\": [\"path\"]\n"
" }\n"
" }\n"
"}\n\n"
"{\n"
" \"type\": \"function\",\n"
" \"function\": {\n"
" \"name\": \"more\",\n"
" \"description\": \"Continue the previous read-like output.\",\n"
" \"parameters\": {\n"
" \"type\": \"object\",\n"
" \"properties\": {\n"
" \"count\": {\"type\": \"number\"}\n"
" }\n"
" }\n"
" }\n"
"}\n\n"
"{\n"
" \"type\": \"function\",\n"
" \"function\": {\n"
" \"name\": \"write\",\n"
" \"description\": \"Create or overwrite a text file.\",\n"
" \"parameters\": {\n"
" \"type\": \"object\",\n"
" \"properties\": {\n"
" \"path\": {\"type\": \"string\"},\n"
" \"content\": {\"type\": \"string\"}\n"
" },\n"
" \"required\": [\"path\", \"content\"]\n"
" }\n"
" }\n"
"}\n\n"
"{\n"
" \"type\": \"function\",\n"
" \"function\": {\n"
" \"name\": \"edit\",\n"
" \"description\": \"Replace exactly one old text match; old may contain [upto] between unique head and tail anchors.\",\n"
" \"parameters\": {\n"
" \"type\": \"object\",\n"
" \"properties\": {\n"
" \"path\": {\"type\": \"string\"},\n"
" \"old\": {\"type\": \"string\"},\n"
" \"new\": {\"type\": \"string\"}\n"
" },\n"
" \"required\": [\"path\", \"old\", \"new\"]\n"
" }\n"
" }\n"
"}\n\n"
"{\n"
" \"type\": \"function\",\n"
" \"function\": {\n"
" \"name\": \"search\",\n"
" \"description\": \"Search files and return compact edit-friendly matches.\",\n"
" \"parameters\": {\n"
" \"type\": \"object\",\n"
" \"properties\": {\n"
" \"query\": {\"type\": \"string\"},\n"
" \"path\": {\"type\": \"string\"},\n"
" \"mode\": {\"type\": \"string\"},\n"
" \"glob\": {\"type\": \"string\"},\n"
" \"context\": {\"type\": \"number\"},\n"
" \"max_results\": {\"type\": \"number\"},\n"
" \"case_sensitive\": {\"type\": \"boolean\"}\n"
" },\n"
" \"required\": [\"query\"]\n"
" }\n"
" }\n"
"}\n\n"
"{\n"
" \"type\": \"function\",\n"
" \"function\": {\n"
" \"name\": \"list\",\n"
" \"description\": \"List one directory compactly.\",\n"
" \"parameters\": {\n"
" \"type\": \"object\",\n"
" \"properties\": {\n"
" \"path\": {\"type\": \"string\"}\n"
" },\n"
" \"required\": [\"path\"]\n"
" }\n"
" }\n"
"}\n"
"\n"
"# Rules\n\n"
"- Always use strict syntax for DSML tool stanzas.\n"
"- This system runs on local inference of a few hundred tokens/s of prefill, "
"and a few tens of tokens/s decoding speed. Use read/search to get the "
"anchors you need, then use anchored edit to avoid having to "
"retype large text.\n"
"- Write code that is reliable and works well; always have a mental model of "
"what is going on in complex parts of the code.\n"
"- Work in a way that preserves the current system configuration integrity, "
"unless explicitly asked otherwise by the user.\n";
static char *agent_build_tools_prompt(void) {
const char *edit = agent_tools_prompt_edit_line;
size_t a = strlen(agent_tools_prompt_intro);
size_t b = strlen(edit);
size_t c = strlen(agent_tools_prompt_after_edit);
char *out = xmalloc(a + b + c + 1);
memcpy(out, agent_tools_prompt_intro, a);
memcpy(out + a, edit, b);
memcpy(out + a + b, agent_tools_prompt_after_edit, c + 1);
return out;
}
static const char agent_dsml_syntax_reminder[] =
"DSML syntax reminder:\n"
"<|DSML|tool_calls>\n"
"<|DSML|invoke name=\"$TOOL_NAME\">\n"
"<|DSML|parameter name=\"$PARAMETER_NAME\" string=\"true|false\">$PARAMETER_VALUE</|DSML|parameter>\n"
"</|DSML|invoke>\n"
"</|DSML|tool_calls>\n";
#define AGENT_SYSTEM_PROMPT_REMINDER_TOKENS 50000
static char *agent_build_system_prompt_reminder(void) {
char *tools = agent_build_tools_prompt();
const char *start = "\n\n[System prompt reminder follows.]\n";
const char *end = "[End system prompt reminder.]\n\n";
size_t len = strlen(start) + strlen(tools) + strlen(end) + 1;
char *out = xmalloc(len);
out[0] = '\0';
strcat(out, start);
strcat(out, tools);
strcat(out, end);
free(tools);
return out;
}
static void agent_append_system_prompt(ds4_engine *engine, ds4_tokens *tokens,
const char *extra) {
/* The built-in tool prompt is trusted DS4 control text. Tokenize it like a
* rendered chat prompt so the literal |DSML| markers in the examples become
* the model's dedicated DSML token. Do not apply that tokenizer to user
* supplied -sys text: arbitrary user text containing <|User|>, <think>, or
* |DSML| must remain plain content, not control tokens. */
char *tools_prompt = agent_build_tools_prompt();
ds4_tokenize_rendered_chat(engine, tools_prompt, tokens);
free(tools_prompt);
if (!extra || !extra[0]) return;
size_t n = strlen(extra);
char *plain = xmalloc(n + 3);
memcpy(plain, "\n\n", 2);
memcpy(plain + 2, extra, n + 1);
ds4_chat_append_message(engine, tokens, "system", plain);