-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.c
More file actions
1414 lines (1220 loc) · 51.4 KB
/
utils.c
File metadata and controls
1414 lines (1220 loc) · 51.4 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
#define _POSIX_C_SOURCE 200809L
#define _DEFAULT_SOURCE
#include "deepshell.h"
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
#include <stdatomic.h>
#include <termios.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
void display_message(const char *message, const char *color) {
if (color) {
printf("%s%s%s\n", color, message, COLOR_RESET);
} else {
printf("%s\n", message);
}
}
void print_colored(const char *text, const char *color) {
if (color) {
printf("%s%s%s\n", color, text, COLOR_RESET);
} else {
printf("%s\n", text);
}
}
void print_markdown(const char *text) {
if (!text) return;
const char *ptr = text;
bool in_code_block = false;
bool in_inline_code = false;
bool in_bold = false;
bool in_italic = false;
bool in_list = false;
bool in_header = false;
bool in_table = false;
bool in_table_header = false;
int header_level = 0;
int line_length = 0;
const int max_line_length = 120; // Prevent excessive line wrapping
while (*ptr) {
// Handle code blocks (```)
if (strncmp(ptr, "```", 3) == 0) {
if (!in_code_block) {
printf("\n%s", COLOR_BLUE);
printf("┌─ Code Block ──────────────────────────────────────────────┐\n");
in_code_block = true;
ptr += 3;
// Skip language identifier (e.g., "markdown", "c", etc.)
while (*ptr && !isspace(*ptr) && *ptr != '\n') {
ptr++;
}
// Skip any remaining whitespace
while (*ptr && isspace(*ptr) && *ptr != '\n') {
ptr++;
}
continue;
} else {
printf("└─────────────────────────────────────────────────────────────┘\n");
printf("%s", COLOR_RESET);
in_code_block = false;
ptr += 3;
continue;
}
}
// Handle inline code (`)
if (*ptr == '`' && !in_code_block) {
if (!in_inline_code) {
printf("%s", COLOR_BLUE);
in_inline_code = true;
} else {
printf("%s", COLOR_RESET);
in_inline_code = false;
}
ptr++;
continue;
}
// Handle bold (**)
if (strncmp(ptr, "**", 2) == 0 && !in_code_block && !in_inline_code) {
if (!in_bold) {
printf("%s", COLOR_YELLOW);
in_bold = true;
} else {
printf("%s", COLOR_RESET);
in_bold = false;
}
ptr += 2;
continue;
}
// Handle italic (*)
if (*ptr == '*' && !in_code_block && !in_inline_code && !in_bold) {
if (!in_italic) {
printf("%s", COLOR_ORANGE);
in_italic = true;
} else {
printf("%s", COLOR_RESET);
in_italic = false;
}
ptr++;
continue;
}
// Handle headers (#)
if (*ptr == '#' && !in_code_block && !in_inline_code) {
header_level = 0;
const char *header_start = ptr;
while (*ptr == '#') {
header_level++;
ptr++;
}
if (header_level <= 6 && *ptr && isspace(*ptr)) {
printf("\n%s", COLOR_GREEN);
for (int i = 0; i < header_level; i++) {
printf("#");
}
printf(" ");
in_header = true;
line_length = 0;
continue;
} else {
ptr = header_start; // Reset if not a valid header
}
}
// Handle lists (- or *)
if ((*ptr == '-' || *ptr == '*') && !in_code_block && !in_inline_code && !in_header) {
const char *list_start = ptr;
ptr++;
if (*ptr && isspace(*ptr)) {
printf("\n%s• ", COLOR_BLUE);
in_list = true;
line_length = 0;
continue;
} else {
ptr = list_start; // Reset if not a valid list
}
}
// Handle numbered lists
if (isdigit(*ptr) && !in_code_block && !in_inline_code && !in_header) {
const char *num_start = ptr;
int num = 0;
while (isdigit(*ptr)) {
num = num * 10 + (*ptr - '0');
ptr++;
}
if (*ptr == '.' && *(ptr + 1) && isspace(*(ptr + 1))) {
printf("\n%s%d. ", COLOR_BLUE, num);
in_list = true;
line_length = 0;
ptr++;
continue;
} else {
ptr = num_start; // Reset if not a valid numbered list
}
}
// Handle horizontal rules (--- or ***)
if ((*ptr == '-' || *ptr == '*') && !in_code_block && !in_inline_code) {
const char *rule_start = ptr;
char rule_char = *ptr;
int rule_count = 0;
while (*ptr == rule_char) {
rule_count++;
ptr++;
}
if (rule_count >= 3 && (*ptr == '\n' || *ptr == '\0')) {
printf("\n%s", COLOR_BLUE);
printf("─────────────────────────────────────────────────────────────\n");
printf("%s", COLOR_RESET);
line_length = 0;
continue;
} else {
ptr = rule_start; // Reset if not a valid rule
}
}
// Handle table separators (|)
if (*ptr == '|' && !in_code_block && !in_inline_code) {
if (!in_table) {
in_table = true;
printf("%s", COLOR_CYAN);
}
printf("│");
line_length++;
ptr++;
continue;
}
// Handle table header separators (|---|)
if (strncmp(ptr, "|---", 4) == 0 && in_table) {
in_table_header = true;
printf("%s", COLOR_CYAN);
printf("├─");
while (*ptr == '-' || *ptr == '|') {
if (*ptr == '|') {
printf("─┤");
} else {
printf("─");
}
ptr++;
}
printf("%s", COLOR_RESET);
line_length = 0;
continue;
}
// Handle HTML-style breaks (<br>)
if (strncmp(ptr, "<br>", 4) == 0 && !in_code_block) {
printf("\n");
line_length = 0;
ptr += 4;
continue;
}
// Handle line breaks
if (*ptr == '\n') {
if (in_list) {
in_list = false;
}
if (in_header) {
in_header = false;
}
if (in_table_header) {
in_table_header = false;
}
if (in_table && !in_table_header) {
in_table = false;
}
printf("\n");
line_length = 0;
ptr++;
continue;
}
// Print the character with smart wrapping
if (line_length >= max_line_length && *ptr == ' ' && !in_code_block) {
printf("\n");
line_length = 0;
}
printf("%c", *ptr);
line_length++;
ptr++;
}
// Reset any active formatting
if (in_code_block || in_inline_code || in_bold || in_italic) {
printf("%s", COLOR_RESET);
}
printf("\n");
}
void animate_progress(const char *status_text) {
// Blue braille Dot Scanner Window (front + rear around status_text)
// Uses small braille dots (not periods), appears on both sides of the text
// and sweeps a denser "window" across a lighter drizzle.
static const char *DOTS_LIGHT[] = {"⠁","⠂","⠄","⡀","⢀","⠠","⠐","⠈"};
static const int DOTS_LIGHT_N = 8;
static const char *DOTS_DENSE[] = {"⠃","⠇","⡇","⣇","⣧","⣷","⣿","⣷","⣧","⣇","⡇","⠇","⠃"};
static const int DOTS_DENSE_N = 13;
const int left_width = 12;
const int right_width = 12;
for (int j = 0; j < 84; j++) {
int win = j % 16;
// Move to line start and set blue
printf("\r%s", COLOR_BLUE);
// Front (left) side
for (int i = 0; i < left_width; i++) {
if (i == win/2 || i == (win/2)+1) {
printf("%s", DOTS_DENSE[(j + i) % DOTS_DENSE_N]);
} else {
printf("%s", DOTS_LIGHT[(j + i) % DOTS_LIGHT_N]);
}
}
// Status text
printf(" %s ", status_text);
// Rear (right) side
for (int i = 0; i < right_width; i++) {
if (i == (15 - win)/2 || i == (15 - win)/2 + 1) {
printf("%s", DOTS_DENSE[(j + i * 2) % DOTS_DENSE_N]);
} else {
printf("%s", DOTS_LIGHT[(j + i * 2) % DOTS_LIGHT_N]);
}
}
// Reset color and clear to end of line for clean rendering
printf("%s\033[K", COLOR_RESET);
fflush(stdout);
usleep(85000);
}
printf("\n");
}
// --- Concurrent progress animation (Dot Scanner Window) ---
static pthread_t g_progress_thread;
static atomic_int g_progress_active = 0;
static atomic_int g_progress_should_run = 0;
static char g_progress_message[1024];
static void* progress_animation_thread(void *arg) {
(void)arg;
// Dot Scanner Window frames (blue only)
static const char *DOTS_LIGHT[] = {"⠁","⠂","⠄","⡀","⢀","⠠","⠐","⠈"};
static const int DOTS_LIGHT_N = 8;
static const char *DOTS_DENSE[] = {"⠃","⠇","⡇","⣇","⣧","⣷","⣿","⣷","⣧","⣇","⡇","⠇","⠃"};
static const int DOTS_DENSE_N = 13;
const int left_width = 12;
const int right_width = 12;
int j = 0;
while (atomic_load(&g_progress_should_run)) {
int win = j % 16;
printf("\r%s", COLOR_BLUE);
// Left band
for (int i = 0; i < left_width; i++) {
if (i == win/2 || i == (win/2)+1) {
printf("%s", DOTS_DENSE[(j + i) % DOTS_DENSE_N]);
} else {
printf("%s", DOTS_LIGHT[(j + i) % DOTS_LIGHT_N]);
}
}
// Message
printf(" %s ", g_progress_message);
// Right band
for (int i = 0; i < right_width; i++) {
if (i == (15 - win)/2 || i == (15 - win)/2 + 1) {
printf("%s", DOTS_DENSE[(j + i * 2) % DOTS_DENSE_N]);
} else {
printf("%s", DOTS_LIGHT[(j + i * 2) % DOTS_LIGHT_N]);
}
}
// Clear rest of line, keep on same line
printf("%s\033[K", COLOR_RESET);
fflush(stdout);
usleep(85000);
j++;
}
return NULL;
}
void start_progress_animation(const char *status_text, bool enable_animation) {
if (!enable_animation) {
return;
}
if (atomic_load(&g_progress_active)) {
return; // already running
}
// Copy message (truncate safely)
size_t len = strlen(status_text);
if (len >= sizeof(g_progress_message)) len = sizeof(g_progress_message) - 1;
memcpy(g_progress_message, status_text, len);
g_progress_message[len] = '\0';
atomic_store(&g_progress_should_run, 1);
if (pthread_create(&g_progress_thread, NULL, progress_animation_thread, NULL) == 0) {
atomic_store(&g_progress_active, 1);
} else {
atomic_store(&g_progress_should_run, 0);
}
}
void stop_progress_animation(void) {
if (!atomic_load(&g_progress_active)) {
return;
}
atomic_store(&g_progress_should_run, 0);
pthread_join(g_progress_thread, NULL);
atomic_store(&g_progress_active, 0);
// Clear the animation line so next output starts cleanly
printf("\r\033[K");
fflush(stdout);
}
void animate_progress_conditional(const char *status_text, bool show_animation) {
if (show_animation) {
animate_progress(status_text);
}
}
char* get_home_directory(void) {
const char *home = getenv("HOME");
if (!home) {
struct passwd *pw = getpwuid(getuid());
if (pw) {
home = pw->pw_dir;
}
}
return home ? strdup_safe(home) : NULL;
}
bool create_directory_if_not_exists(const char *path) {
struct stat st = {0};
if (stat(path, &st) == -1) {
if (mkdir(path, 0700) == 0) {
return true;
} else {
return false;
}
}
return true;
}
char* read_line(void) {
char *line = readline("");
if (line && *line) {
// Add to history if non-empty
add_history(line);
}
return line;
}
void clear_screen(void) {
printf("\033[2J\033[H");
}
bool is_valid_url(const char *url) {
if (!url) return false;
// Basic URL validation
if (strncmp(url, "http://", 7) == 0 || strncmp(url, "https://", 8) == 0) {
return true;
}
// Check if it looks like a hostname:port
if (strchr(url, ':') != NULL) {
return true;
}
return false;
}
char* trim_whitespace(char *str) {
if (!str) return NULL;
char *end;
// Trim leading space
while (isspace((unsigned char)*str)) str++;
if (*str == 0) return str; // All spaces
// Trim trailing space
end = str + strlen(str) - 1;
while (end > str && isspace((unsigned char)*end)) end--;
// Write new null terminator
end[1] = '\0';
return str;
}
char* strdup_safe(const char *str) {
if (!str) return NULL;
size_t len = strlen(str) + 1;
char *dup = malloc(len);
if (dup) {
strcpy(dup, str);
}
return dup;
}
// HTTP utility functions
struct curl_slist* create_headers(void) {
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "Accept: application/json");
return headers;
}
void free_headers(struct curl_slist *headers) {
if (headers) {
curl_slist_free_all(headers);
}
}
size_t write_callback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
char **response_ptr = (char**)userp;
size_t current_len = (*response_ptr) ? strlen(*response_ptr) : 0;
char *new_response = realloc(*response_ptr, current_len + realsize + 1);
if (!new_response) {
return 0; // Out of memory
}
*response_ptr = new_response;
memcpy(&(*response_ptr)[current_len], contents, realsize);
(*response_ptr)[current_len + realsize] = 0;
return realsize;
}
bool make_http_request(const char *url, const char *post_data,
struct curl_slist *headers, char **response) {
CURL *curl = curl_easy_init();
if (!curl) {
return false;
}
*response = malloc(1);
(*response)[0] = '\0';
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, response);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L); // Extended timeout for slower models
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10L); // Extended connection timeout
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L); // Enable keep-alive
if (headers) {
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
}
if (post_data) {
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data);
}
CURLcode res = curl_easy_perform(curl);
long http_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
curl_easy_cleanup(curl);
if (res != CURLE_OK) {
display_message("HTTP request failed: ", COLOR_RED);
printf("%s\n", curl_easy_strerror(res));
free(*response);
*response = NULL;
return false;
}
if (http_code < 200 || http_code >= 300) {
display_message("HTTP request failed with status code: ", COLOR_RED);
printf("%ld\n", http_code);
if (*response) {
display_message("Response: ", COLOR_RED);
printf("%s\n", *response);
}
free(*response);
*response = NULL;
return false;
}
return true;
}
char* extract_response_from_json(json_object *json_obj, const char *service) {
if (strcmp(service, LLM_SERVICE_OLLAMA) == 0) {
json_object *message_obj, *content_obj;
if (json_object_object_get_ex(json_obj, "message", &message_obj)) {
if (json_object_object_get_ex(message_obj, "content", &content_obj)) {
const char *content = json_object_get_string(content_obj);
return strdup_safe(content);
}
}
} else if (strcmp(service, LLM_SERVICE_GEMINI) == 0) {
json_object *candidates_array, *candidate, *content, *parts_array, *part, *text_obj;
if (json_object_object_get_ex(json_obj, "candidates", &candidates_array) &&
json_object_array_length(candidates_array) > 0) {
candidate = json_object_array_get_idx(candidates_array, 0);
if (json_object_object_get_ex(candidate, "content", &content)) {
if (json_object_object_get_ex(content, "parts", &parts_array) &&
json_object_array_length(parts_array) > 0) {
part = json_object_array_get_idx(parts_array, 0);
if (json_object_object_get_ex(part, "text", &text_obj)) {
const char *text = json_object_get_string(text_obj);
return strdup_safe(text);
}
}
}
}
} else if (strcmp(service, LLM_SERVICE_OPENROUTER) == 0) {
// OpenRouter uses OpenAI-compatible format
json_object *choices_array, *choice, *message_obj, *content_obj;
if (json_object_object_get_ex(json_obj, "choices", &choices_array) &&
json_object_array_length(choices_array) > 0) {
choice = json_object_array_get_idx(choices_array, 0);
if (json_object_object_get_ex(choice, "message", &message_obj)) {
if (json_object_object_get_ex(message_obj, "content", &content_obj)) {
const char *content = json_object_get_string(content_obj);
return strdup_safe(content);
}
}
}
}
return NULL;
}
// Safe string concatenation that handles special characters
char* safe_concat_query(int argc, char *argv[], int start_index) {
size_t total_len = 0;
// First pass: calculate total length needed
for (int j = start_index; j < argc; j++) {
total_len += strlen(argv[j]) + 1; // +1 for space
}
char *result = malloc(total_len + 1);
if (!result) return NULL;
result[0] = '\0';
// Second pass: concatenate with proper spacing
for (int j = start_index; j < argc; j++) {
if (j > start_index) {
strcat(result, " ");
}
strcat(result, argv[j]);
}
return result;
}
// Command line argument parsing
cli_args_t parse_arguments(int argc, char *argv[]) {
cli_args_t args = {0};
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--setup") == 0) {
args.setup = true;
} else if (strcmp(argv[i], "-i") == 0 || strcmp(argv[i], "--interactive") == 0) {
args.interactive = true;
} else if (strcmp(argv[i], "-q") == 0 || strcmp(argv[i], "--query") == 0) {
args.query = true;
// Collect all remaining arguments as the query using safe concatenation
if (i + 1 < argc) {
args.query_text = safe_concat_query(argc, argv, i + 1);
break; // We've processed all remaining arguments
}
} else if (strcmp(argv[i], "-a") == 0 || strcmp(argv[i], "--active-config") == 0) {
args.active_config = true;
} else if (strcmp(argv[i], "-b") == 0 || strcmp(argv[i], "--export") == 0) {
args.export_config = true;
// Get the next argument as filename
if (i + 1 < argc) {
args.config_filename = strdup(argv[i + 1]);
i++; // Skip the filename argument
}
} else if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--import") == 0) {
args.import_config = true;
// Get the next argument as filename
if (i + 1 < argc) {
args.config_filename = strdup(argv[i + 1]);
i++; // Skip the filename argument
}
} else if (strcmp(argv[i], "-d") == 0 || strcmp(argv[i], "--delete-config") == 0) {
args.delete_config = true;
} else if (strcmp(argv[i], "-show-key") == 0 || strcmp(argv[i], "--show-api-key") == 0) {
args.show_gemini_key = true;
} else if (strcmp(argv[i], "-set-key") == 0 || strcmp(argv[i], "--set-api-key") == 0) {
args.set_gemini_key = true;
} else if (strcmp(argv[i], "-gq") == 0 || strcmp(argv[i], "--gemini-quota") == 0) {
args.gemini_quota_check = true;
} else if (strcmp(argv[i], "-l") == 0 || strcmp(argv[i], "--llm") == 0) {
args.switch_llm = true;
} else if (strcmp(argv[i], "-show-config") == 0 || strcmp(argv[i], "--show-full-conf") == 0) {
args.show_config = true;
} else if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--version") == 0) {
args.version = true;
} else if (strcmp(argv[i], "-j") == 0 || strcmp(argv[i], "--jump-llm") == 0) {
args.jump_llm = true;
} else if (strcmp(argv[i], "-m") == 0 || strcmp(argv[i], "--model-change") == 0) {
args.model_change = true;
} else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
args.help = true;
} else if (strncmp(argv[i], "-q=", 3) == 0 || strncmp(argv[i], "--query=", 8) == 0) {
// Handle quoted query format: -q="query text" or --query="query text"
args.query = true;
const char *query_start = (argv[i][1] == 'q') ? argv[i] + 3 : argv[i] + 8;
if (strlen(query_start) > 0) {
args.query_text = strdup(query_start);
}
} else if (strcmp(argv[i], "--no-animation") == 0) {
args.no_animation = true;
}
}
return args;
}
void free_cli_args(cli_args_t *args) {
if (args->query_text) {
free(args->query_text);
args->query_text = NULL;
}
if (args->config_filename) {
free(args->config_filename);
args->config_filename = NULL;
}
}
// Get user's Downloads directory
char* get_downloads_path(void) {
const char *home = getenv("HOME");
if (!home) {
return NULL;
}
char *downloads_path = malloc(strlen(home) + strlen("/Downloads") + 1);
if (!downloads_path) {
return NULL;
}
strcpy(downloads_path, home);
strcat(downloads_path, "/Downloads");
return downloads_path;
}
// Save last response to markdown file
bool save_response_to_file(const char *response_text, const char *filename) {
if (!response_text || !filename) {
return false;
}
// Get Downloads directory first, fallback to home directory
char *downloads_path = get_downloads_path();
char *target_dir = downloads_path;
if (!target_dir) {
// Fallback to home directory
target_dir = get_home_directory();
if (!target_dir) {
display_message("Failed to get home directory.", COLOR_RED);
return false;
}
}
// Create full file path
char *full_path = malloc(strlen(target_dir) + strlen(filename) + 2);
if (!full_path) {
display_message("Memory allocation failed.", COLOR_RED);
if (downloads_path) free(downloads_path);
if (!downloads_path) free(target_dir);
return false;
}
strcpy(full_path, target_dir);
strcat(full_path, "/");
strcat(full_path, filename);
// Check if file already exists
if (access(full_path, F_OK) == 0) {
display_message("File already exists. Overwrite? (y/N): ", COLOR_YELLOW);
char *confirm = read_line();
if (!confirm || (confirm[0] != 'y' && confirm[0] != 'Y')) {
display_message("Convert cancelled.", COLOR_YELLOW);
free(confirm);
free(full_path);
if (downloads_path) free(downloads_path);
if (!downloads_path) free(target_dir);
return false;
}
free(confirm);
}
// Write the response to file
FILE *file = fopen(full_path, "w");
if (!file) {
display_message("Failed to create file.", COLOR_RED);
free(full_path);
if (downloads_path) free(downloads_path);
if (!downloads_path) free(target_dir);
return false;
}
// Write the raw response text (not terminal-formatted)
fprintf(file, "%s\n", response_text);
fclose(file);
display_message("Save successful!", COLOR_GREEN);
display_message("File saved to: ", COLOR_BLUE);
printf("%s\n", full_path);
free(full_path);
if (downloads_path) free(downloads_path);
if (!downloads_path) free(target_dir);
return true;
}
// Validate filename for save command
bool is_valid_filename(const char *filename) {
if (!filename || strlen(filename) == 0) {
return false;
}
// Check for invalid characters
const char *invalid_chars = "/\\:*?\"<>|";
for (int i = 0; invalid_chars[i]; i++) {
if (strchr(filename, invalid_chars[i])) {
return false;
}
}
// Check if it's just dots or spaces
bool has_valid_char = false;
for (int i = 0; filename[i]; i++) {
if (filename[i] != '.' && filename[i] != ' ') {
has_valid_char = true;
break;
}
}
return has_valid_char;
}
// Read file content for open command
char* read_file_content(const char *filepath) {
if (!filepath) {
return NULL;
}
// Check if file exists
if (access(filepath, F_OK) != 0) {
display_message("Error: File does not exist.", COLOR_RED);
return NULL;
}
// Check if file is readable
if (access(filepath, R_OK) != 0) {
display_message("Error: File cannot be read (permission denied).", COLOR_RED);
return NULL;
}
// Get file size
struct stat file_stat;
if (stat(filepath, &file_stat) != 0) {
display_message("Error: Cannot get file information.", COLOR_RED);
return NULL;
}
// Check file size (25MB limit)
const off_t max_size = 25 * 1024 * 1024; // 25MB
if (file_stat.st_size > max_size) {
display_message("Error: File too large (max 25MB).", COLOR_RED);
return NULL;
}
// Open file
FILE *file = fopen(filepath, "r");
if (!file) {
display_message("Error: Cannot open file.", COLOR_RED);
return NULL;
}
// Allocate memory for content
char *content = malloc(file_stat.st_size + 1);
if (!content) {
display_message("Error: Not enough memory to read file.", COLOR_RED);
fclose(file);
return NULL;
}
// Read file content
size_t bytes_read = fread(content, 1, file_stat.st_size, file);
fclose(file);
if (bytes_read != (size_t)file_stat.st_size) {
display_message("Error: Failed to read complete file.", COLOR_RED);
free(content);
return NULL;
}
content[bytes_read] = '\0';
return content;
}
// Check if file is text-based
bool is_text_file(const char *filepath) {
if (!filepath) {
return false;
}
FILE *file = fopen(filepath, "r");
if (!file) {
return false;
}
// Read first 1024 bytes to check for binary content
char buffer[1024];
size_t bytes_read = fread(buffer, 1, sizeof(buffer), file);
fclose(file);
if (bytes_read == 0) {
return true; // Empty file is considered text
}
// Check for null bytes (indicates binary file)
for (size_t i = 0; i < bytes_read; i++) {
if (buffer[i] == '\0') {
return false;
}
}
return true;
}
// Display interactive mode help menu
void display_interactive_help(void) {
printf("\n");
display_message("--- DeepShell Interactive Mode Commands ---", COLOR_GREEN);
printf("\n");
printf("Available Commands:\n");
printf(" exit, quit End the interactive session and return to command line\n");
printf(" help Show this help message with all available commands\n");
printf(" save [filename] Save the last LLM response to a markdown file\n");
printf(" open [filepath] Open a text file and process it as input to the LLM\n");
printf("\n");
printf("Command Details:\n");
printf(" exit/quit:\n");
printf(" - Ends the current interactive session\n");
printf(" - Returns to the command line\n");
printf(" - Conversation history is cleared (not saved between sessions)\n");
printf("\n");
printf(" help:\n");
printf(" - Displays this comprehensive help menu\n");
printf(" - Shows all available interactive commands\n");
printf(" - Provides detailed usage information\n");
printf("\n");
printf(" save [filename]:\n");
printf(" - Saves the last LLM response to a markdown file\n");
printf(" - Automatically adds .md extension if not provided\n");
printf(" - Saves to Downloads folder (falls back to home directory)\n");
printf(" - Asks for confirmation before overwriting existing files\n");
printf(" - Validates filenames for invalid characters\n");
printf(" - Example: 'save my-notes' → saves as 'my-notes.md'\n");
printf("\n");
printf(" open [filepath]:\n");
printf(" - Opens a text file and processes it as input to the LLM\n");
printf(" - Supports both absolute and relative file paths\n");
printf(" - Validates file exists, is readable, and is text-based\n");
printf(" - Prompts for instructions on how to process the file\n");
printf(" - Combines your instructions with file content for the LLM\n");
printf(" - Example: 'open /home/user/data.txt'\n");
printf(" - Example: 'open ../documents/notes.md'\n");
printf("\n");
printf("Usage Tips:\n");
printf(" - Type any text to send as a query to the active LLM\n");
printf(" - Use 'save' to preserve important responses for later reference\n");
printf(" - Use 'open' to analyze files, documents, or code with the LLM\n");
printf(" - Use 'help' anytime to see this command reference\n");
printf(" - Use 'exit' or 'quit' to end the session\n");
printf("\n");
}
// Get password input with optional confirmation
char* get_password_input(const char *prompt, bool confirm) {
printf("%s", prompt);
fflush(stdout);
// Turn off echo
struct termios old, new;
tcgetattr(STDIN_FILENO, &old);
new = old;
new.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &new);
char *password = read_line();
// Turn echo back on
tcsetattr(STDIN_FILENO, TCSANOW, &old);
printf("\n");
if (!password || strlen(password) == 0) {
if (password) free(password);
return NULL;
}
if (confirm) {
printf("Confirm password: ");
fflush(stdout);
// Turn off echo again
tcsetattr(STDIN_FILENO, TCSANOW, &new);
char *confirm_password = read_line();
tcsetattr(STDIN_FILENO, TCSANOW, &old);
printf("\n");
if (!confirm_password || strcmp(password, confirm_password) != 0) {
display_message("Passwords do not match.", COLOR_RED);
free(password);
if (confirm_password) free(confirm_password);
return NULL;