This repository was archived by the owner on Nov 18, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgem-cli
More file actions
executable file
·2005 lines (1843 loc) · 53.3 KB
/
gem-cli
File metadata and controls
executable file
·2005 lines (1843 loc) · 53.3 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
#!/bin/bash
################################################################################
# #
# Gemini CLI #
# #
# Command-line AI assistant powered by Google Gemini. #
# #
# Copyright (C) 2025 Jore <https://github.com/jorexdeveloper> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <https://www.gnu.org/licenses/>. #
# #
################################################################################
# shellcheck disable=SC2329,SC2155
################################################################################
# Initializes chat history. #
# #
# Args: #
# OPTIONS (see case inside) #
# Sets: #
# CHAT_HISTORY - Array containing chat entries. #
################################################################################
init_history() {
local from=init_history
if [[ ${HISTORY_ENABLED} ]]; then
log -i "Initializing chat history."
local use_file=
while getopts ":f" opt; do
case "${opt}" in
f) use_file=1 ;;
*) ;;
esac
done
shift $((OPTIND - 1))
unset OPTIND
if [[ ${use_file} && ${HISTORY_FILE_ENABLED} && -f ${HISTORY_FILE} ]]; then
if [[ $(jq -r 'type' "${HISTORY_FILE}" 2>/dev/null) == array ]]; then
log -df "${from}" "Reading chat history from file: ${HISTORY_FILE}"
CHAT_HISTORY=$(jq -c '.' "${HISTORY_FILE}")
return
else
log -e "Failed to read chat history from file: ${HISTORY_FILE}"
fi
fi
log -df "${from}" "Creating empty chat history."
CHAT_HISTORY=[]
fi
}
################################################################################
# Adds entries to chat history. #
# #
# Args: #
# OPTIONS (see case inside) #
# Arrays containing chat entries. #
# Returns: #
# 1 - Failed to add entries to chat history. #
# 2 - Failed to write chat history to file. #
################################################################################
add_to_history() {
local from=add_to_history
if [[ ${HISTORY_ENABLED} ]]; then
log -i "Adding entries to chat history."
local write_file=
while getopts ":w" opt; do
case "${opt}" in
w) write_file=1 ;;
*) ;;
esac
done
shift $((OPTIND - 1))
unset OPTIND
log -df "${from}" "Adding ${#} entries to chat history."
if CHAT_HISTORY=$(
jq \
-nc \
--argjson CHAT_HISTORY "${CHAT_HISTORY}" \
'[$CHAT_HISTORY[], $ARGS.positional[][]]' \
--jsonargs -- "${@}"
); then
if [[ ${write_file} && ${HISTORY_FILE_ENABLED} && ${HISTORY_FILE} ]]; then
log -df "${from}" "Writing chat history to file: ${HISTORY_FILE}"
if ! {
mkdir -p "${HISTORY_DIR}" &&
printf %s "${CHAT_HISTORY}" >"${HIST_TEMP_FILE}" &&
mv -f "${HIST_TEMP_FILE}" "${HISTORY_FILE}"
}; then
log -e "Failed to write chat history to file: ${HISTORY_FILE}"
return 2
fi
fi
else
log -e "Failed to add ${#} entries to chat history."
return 1
fi
fi
}
################################################################################
# Creates a new chat. #
# #
# Args: #
# OPTIONS (see case inside) #
# Returns: #
# 1 - Failed to backup current chat history. #
# 2 - Failed to clear history file. #
################################################################################
create_new_chat() {
local from=create_new_chat
if [[ ${HISTORY_ENABLED} ]]; then
log -i "Creating new chat."
local write_file=
local backup_current=
while getopts ":wb" opt; do
case "${opt}" in
w) write_file=1 ;;
b) backup_current=1 ;;
*) ;;
esac
done
shift $((OPTIND - 1))
unset OPTIND
if [[ ${write_file} && ${HISTORY_FILE_ENABLED} && -f ${HISTORY_FILE} ]]; then
if [[ ${backup_current} ]]; then
local file="${HISTORY_DIR}"/chat-"$(date +'%Y%m%d%H%M%S')".json
log -df "${from}" "Backing up current history to file: ${file}"
if ! {
mkdir -p "${HISTORY_DIR}" &&
mv -f "${HISTORY_FILE}" "${file}"
}; then
log -e "Failed to backup current history to file: ${file}"
return 1
fi
fi
log -df "${from}" "Clearing chat history in file: ${HISTORY_FILE}"
if ! rm -f "${HISTORY_FILE}"; then
log -e "Failed to clear chat history in file: ${HISTORY_FILE}"
return 2
fi
fi
init_history
fi
}
################################################################################
# Creates an array containing a chat entry. #
# #
# Args: #
# OPTIONS (see case inside) #
# Parts of the chat entry text. #
# Sets: #
# CHAT_ENTRY - An array containing the chat entry. #
# Returns: #
# 1 - Failed to create chat entry. #
################################################################################
create_entry() {
local from=create_entry
log -i "Creating chat entry."
local role=user
while getopts ":um" opt; do
case "${opt}" in
u) role=user ;;
m) role=model ;;
*) ;;
esac
done
shift $((OPTIND - 1))
unset OPTIND
log -df "${from}" "Creating chat entry for '${role}'."
if ! CHAT_ENTRY=$(
jq \
-nc \
--arg role "${role}" \
'[{role: $role, parts: [{text: $ARGS.positional[]}]}]' \
--args -- "${@}"
); then
log -e "Failed to create chat entry for '${role}'."
return 1
fi
}
################################################################################
# Gets a JSON array of supported API models. #
# #
# Sets: #
# API_RESPONSE - Raw API response. #
# API_MESSAGE - API models/Error message. #
# Returns: #
# 1 - Failed to get API response. #
# 2 - Received empty API response. #
# 3 - The API returned an error. #
# 4 - Invalid API response. #
################################################################################
get_models() {
local from=get_models
log -i "Getting supported API models."
API_RESPONSE=
API_MESSAGE=
log -df "${from}" "Sending request to API."
trap 'trap - INT; API_MESSAGE="Failed to get API response. Please check your internet connection and try again."; return 1' INT
while true; do
if API_RESPONSE=$(
curl \
-s \
-H "x-goog-api-key: ${GEMINI_API_KEY}" \
"${API_URL}/${API_VERSION}/models"
); then
trap - INT
break
elif [[ ${RETRY_CONN_ERROR} ]]; then
continue
else
trap - INT
API_MESSAGE="Failed to get API response. Please check your internet connection and try again."
return 1
fi
done
log -df "${from}" "Processing API response."
if [[ ! ${API_RESPONSE} ]]; then
API_MESSAGE="Received empty API response."
return 2
fi
log -df "${from}" "Checking for API error."
local error
if error=$(
jq \
-nre \
--argjson API_RESPONSE "${API_RESPONSE}" \
'$API_RESPONSE.error.message // empty'
); then
log -df "${from}" "Processing API error."
API_MESSAGE=${error}
return 3
fi
log -df "${from}" "Extracting supported API models."
if ! API_MESSAGE=$(
jq \
-ne \
--argjson API_RESPONSE "${API_RESPONSE}" \
"[\$API_RESPONSE.models[] | select(.supportedGenerationMethods | contains([\"${API_METHOD}\"]))]"
); then
log -df "${from}" "Creating ERROR 4 message."
API_MESSAGE="Received invalid API response."
return 4
fi
}
################################################################################
# Gets the API response for chat entries. #
# #
# Args: #
# Arrays containing chat entries. #
# Sets: #
# API_RESPONSE - Raw API response. #
# API_MESSAGE - API/Error message. #
# Returns: #
# 1 - Failed to get API response. #
# 2 - Received empty API response. #
# 3 - The API returned an error. #
# 4 - Invalid API response. #
################################################################################
get_response() {
local from=get_response
log -i "Getting API response for chat entries."
API_RESPONSE=
API_MESSAGE=
log -df "${from}" "Creating JSON payload from chat entries."
local json_payload=$(
jq \
-nc \
'{contents: [$ARGS.positional[].[]]}' \
--jsonargs -- "${@}"
)
log -df "${from}" "Sending JSON payload to API."
trap 'trap - INT; API_MESSAGE="Failed to get API response. Please check your internet connection and try again."; return 1' INT
while true; do
if API_RESPONSE=$(
curl \
-s \
-X POST \
-d "${json_payload}" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: ${GEMINI_API_KEY}" \
"${API_URL}/${API_VERSION}/${API_MODEL}:${API_METHOD}"
); then
trap - INT
break
elif [[ ${RETRY_CONN_ERROR} ]]; then
continue
else
trap - INT
API_MESSAGE="Failed to get API response. Please check your internet connection and try again."
return 1
fi
done
log -df "${from}" "Processing API response."
if [[ ! ${API_RESPONSE} ]]; then
API_MESSAGE="Received empty API response."
return 2
fi
log -df "${from}" "Checking for API error."
local error
if error=$(
jq \
-nre \
--argjson API_RESPONSE "${API_RESPONSE}" \
'$API_RESPONSE.error.message // empty'
); then
log -df "${from}" "Processing API error."
API_MESSAGE=${error}
return 3
fi
log -df "${from}" "Extracting API text."
if ! API_MESSAGE=$(
jq \
-nre \
--argjson API_RESPONSE "${API_RESPONSE}" \
'$API_RESPONSE.candidates[0].content.parts[].text // empty'
); then
log -df "${from}" "Creating ERROR 4 message."
API_MESSAGE="Received invalid API response."
return 4
fi
}
################################################################################
# Handles API errors. #
################################################################################
api_error() {
local from=api_error
log -ef API "$(
jq \
-nrj \
--arg API_MESSAGE "${API_MESSAGE}" \
--argjson API_RESPONSE "${API_RESPONSE}" \
'$API_RESPONSE | .error.status, " (", .error.code, ") ", .error.message'
)"
}
################################################################################
# Handles invalid API responses. #
# #
# Returns: #
# 1 - Failed to save invalid API response. #
################################################################################
invalid_response() {
local from=invalid_response
log -e "${API_MESSAGE}"
local dir="${SOURCE_DIR}"/invalid_responses
local file="${dir}/response-$(date +'%Y%m%d%H%M%S').json"
log -df "${from}" "Saving invalid API response to file: ${file}"
if ! {
mkdir -p "${dir}" &&
printf %s "${API_RESPONSE}" >"${file}"
}; then
log -e "Failed to save invalid API response to file: ${file}."
return 1
fi
}
################################################################################
# Saves API response with chat entries to a file. #
# #
# Args: #
# Arrays containing chat entries. #
# Returns: #
# 1 - API response saving disabled. #
# 2 - Failed to save API response. #
################################################################################
save_response() {
local from=save_response
if [[ ${SAVE_RESPONSE} ]]; then
log -i "Saving API response."
local file="${RESPONSE_DIR}/response-$(date +'%Y%m%d%H%M%S').json"
log -df "${from}" "Saving API response to file: ${file}"
if ! {
mkdir -p "${RESPONSE_DIR}" &&
jq \
-nc \
--argjson response "${API_RESPONSE}" \
'{contents: [$ARGS.positional[].[]], response: $response}' \
--jsonargs -- "${@}" \
>"${file}"
}; then
log -e "Failed to save API response to file: ${file}."
return 2
fi
else
return 1
fi
}
################################################################################
# Prints API response. #
# #
# Args: #
# OPTIONS to forward to msg() #
# Extras: #
# Handles JSON_RESPONSE #
################################################################################
print_response() {
local from=print_response
log -i "Printing API response."
if [[ ${JSON_RESPONSE} ]]; then
log -df "${from}" "Creating JSON response."
create_entry -m -- "${API_MESSAGE}"
jq \
-n \
--argjson API_MESSAGE "${CHAT_ENTRY}" \
'$API_MESSAGE'
else
msg -m "${@}" -- "${API_MESSAGE}" | ${PAGER} "${PAGER_ARGS[@]}"
fi
}
################################################################################
# Prints API usage stats. #
# #
# Args: #
# OPTIONS to forward to msg() #
# Returns: #
# 1 - API usage stats disabled. #
################################################################################
print_usage_stats() {
local from=print_usage_stats
if ! [[ ${RAW_OUTPUT} || ${QUIET} || ! ${API_RESPONSE} ]]; then
log -i "Printing API usage stats."
log -df "${from}" "Extracting API usage stats."
msg "${@}" -- "Used $(
jq \
-nr \
--argjson API_RESPONSE "${API_RESPONSE}" \
'$API_RESPONSE.usageMetadata.totalTokenCount // 0'
) Tokens"
else
return 1
fi
}
################################################################################
# Prints chat entries. #
# #
# Args: #
# Arrays containing chat entries. #
# Returns: #
# 1 - Chat history disabled. #
# Extras: #
# Handles JSON_RESPONSE #
################################################################################
print_chat() {
local from=print_chat
if [[ ${HISTORY_ENABLED} && ${CHAT_HISTORY} ]]; then
log -i "Printing chat entries."
log -df "${from}" "Extracting chat entries."
if [[ ${JSON_RESPONSE} ]]; then
if [[ ${*} != [] ]]; then
jq \
-n \
'[$ARGS.positional[][]]' \
--jsonargs -- "${@}"
fi
else
log -df "${from}" "Extracting messages from chat entries."
local arg indices index role message
for arg in "${@}"; do
# shellcheck disable=SC2207
indices=($(jq -nr --argjson arg "${arg}" '$arg | keys[]'))
for index in "${indices[@]}"; do
role=$(
jq \
-nr \
--argjson index "${index}" \
--argjson arg "${arg}" \
'$arg[$index].role | .[0:1]'
)
message=$(
jq \
-nr \
--argjson index "${index}" \
--argjson arg "${arg}" \
'$arg[$index].parts[0].text'
)
if [[ ${PRINT_CHAT_NO_FIRST_LINE} && ${index} -eq 0 ]]; then
msg -"${role}" -- "${message}"
else
msg -l"${role}" -- "${message}"
fi
if [[ ${CHAT_SEPARATOR} && ${role} == m ]]; then
msg -S
fi
done
done
fi
else
return 1
fi
}
################################################################################
# Prints message header. #
# #
# Args: #
# OPTIONS to forward to msg() #
# Returns: #
# 1 - Header disabled. #
# Extras: #
# Handles RAW_INPUT #
################################################################################
header() {
local from=header
if ! [[ ${QUIET} || ${RAW_OUTPUT} ]]; then
log -df "${from}" "Printing header."
msg -h "${@}" "${NAME} ${VERSION} (${API_MODEL/models\//})"
else
return 1
fi
}
################################################################################
# Prints message to standard output. #
# #
# Args: #
# OPTIONS (see case inside) #
# Message to be printed. #
# Extras: #
# Handles RAW_INPUT #
# Handles JSON_RESPONSE (But NOT recommended) #
# BUG: #
# Syntax highlighting does NOT respect split lines after fmt. #
################################################################################
msg() {
local from=msg
if [[ ${RAW_OUTPUT} ]]; then
H_PREFIX=
N_PREFIX=
I_PREFIX=
F_PREFIX=
M_PREFIX=
U_PREFIX=
E_PREFIX=
H_PROMPT=
N_PROMPT=
I_PROMPT=
F_PROMPT=
M_PROMPT=
U_PROMPT=
E_PROMPT=
else
H_PREFIX=" "
N_PREFIX=" "
I_PREFIX=" "
F_PREFIX=" "
M_PREFIX="${BBG3} ${BGR}"
U_PREFIX="${BBG5} ${BGR}"
E_PREFIX="${BBG1} ${BGR}"
H_PROMPT=" "
N_PROMPT=" "
I_PROMPT=" "
F_PROMPT=" "
M_PROMPT=" "
U_PROMPT=" "
E_PROMPT=" "
fi
local role=${NAME}
local dtc=${FG7}
local text_color=${dtc}
local dpc=${BFG0}
local prompt_color=${dpc}
local prompt=${N_PROMPT}
local prefix=${N_PREFIX}
local separator_before=
local separator_after=
local empty_line_before=
local empty_line_after=
local r_before=
local n_after=1
while getopts ":hHiIfFmMuUeEsSlLrn" opt; do
case "${opt}" in
h)
# Header
text_color=${BFG4}
prompt_color=${BFG4}
prompt=${H_PROMPT}
prefix=${H_PREFIX}
;;
H)
# Header (no prompt)
text_color=${BFG4}
prompt_color=${BFG4}
prompt=${H_PROMPT}
prefix=${H_PREFIX}
;;
i)
# Info
text_color=${BFG0}
prompt_color=${BFG0}
prompt=${I_PROMPT}
prefix=${I_PREFIX}
;;
I)
# Info (no prompt)
text_color=${BFG0}
prompt_color=${BFG0}
prompt=${I_PROMPT}
prefix=${I_PREFIX}
;;
f)
# Footer
text_color=${dtc}
prompt_color=${dpc}
prompt=${F_PROMPT}
prefix=${F_PREFIX}
;;
F)
# Footer (no prompt)
text_color=${dtc}
prompt_color=${dpc}
prompt=${F_PROMPT}
prefix=${F_PREFIX}
;;
m)
# Model
text_color=${FG7}
prompt_color=${BFG3}
prompt=${M_PROMPT}
prefix=${M_PREFIX}
role=model
;;
M)
# Model (no prompt)
text_color=${FG7}
prompt_color=${BFG3}
prompt=${M_PROMPT}
prefix=${M_PREFIX}
role=model
;;
u)
# User
text_color=${FG7}
prompt_color=${BFG5}
prompt=${U_PROMPT}
prefix=${U_PREFIX}
role=user
;;
U)
# User (no prompt)
text_color=${FG7}
prompt_color=${BFG5}
prompt=${M_PROMPT}
prefix=${U_PREFIX}
role=user
;;
e)
# Error
text_color=${FG7}
prompt_color=${BFG1}
prompt=${E_PROMPT}
prefix=${E_PREFIX}
;;
E)
# Error (no prompt)
text_color=${FG7}
prompt_color=${BFG1}
prompt=${E_PROMPT}
prefix=${E_PREFIX}
;;
s)
# Print separator before
separator_before=1
;;
S)
# Print separator after
separator_after=1
;;
l)
# Print empty line before (formatted)
empty_line_before=1
;;
L)
# Print empty line after (formatted)
empty_line_after=1
;;
r)
# Print \r before
r_before=1
;;
n)
# Don't print \n after (like read -p)
n_after=
;;
*) ;;
esac
done
shift $((OPTIND - 1))
unset OPTIND
if [[ ${JSON_RESPONSE} ]]; then
if [[ ${*} ]]; then
if [[ "${role}" == model ]]; then
create_entry -m -- "${*}"
else
create_entry -u -- "${*}"
fi
jq \
-n \
--argjson CHAT_ENTRY "${CHAT_ENTRY}" \
'$CHAT_ENTRY'
fi
else
if [[ ${RAW_OUTPUT} && ${TERM_OUTPUT} ]]; then
text_color=${prompt_color}
fi
if [[ ${RAW_OUTPUT} ]]; then
size=${TERM_WIDTH}
else
size=$((TERM_WIDTH - (${#N_PREFIX} + ${#N_PROMPT})))
fi
print_separator() {
if [[ ! ${RAW_OUTPUT} ]]; then
local i=${size}
local s=
while [[ ${i} -gt 2 ]]; do
s+=—
((i--))
done
else
s=---
fi
printf "${N_PREFIX}${dpc}${N_PROMPT}${R}%s" "${s}"
}
if [[ ${empty_line_before} ]]; then
printf "${N_PREFIX}${dpc}${N_PROMPT}${R}%s\n"
fi
if [[ ${separator_before} ]]; then
print_separator
printf \\n
fi
if [[ ${r_before} ]]; then
printf \\r
fi
local line
local pref=${prefix}
if [[ ${RAW_OUTPUT} ]]; then
printf %s\\n "${*}" | ${HIGHLIGTER} "${HIGHLIGTER_ARGS[@]}"
else
printf %s\\n "${*}" | fmt -sw "${size}" -g "${size}" | ${HIGHLIGTER} "${HIGHLIGTER_ARGS[@]}"
fi | sed "s/^//" |
while read -r line; do
printf "${pref}${prompt_color}${prompt}${text_color}%s${R}" "${line}"
prompt=${N_PROMPT}
pref=\\n${prefix}
done | sed "s///"
if [[ ${separator_after} ]]; then
printf \\n
print_separator
fi
if [[ ${empty_line_after} ]]; then
printf "\n${N_PREFIX}${dpc}${N_PROMPT}${R}%s"
fi
if [[ ${n_after} ]]; then
printf \\n
fi
fi
}
################################################################################
# Prints message footer. #
# #
# Args: #
# OPTIONS to forward to msg() #
# Returns: #
# 1 - Footer disabled. #
################################################################################
footer() {
local from=footer
if ! [[ ${QUIET} || ${RAW_OUTPUT} ]]; then
log -df "${from}" "Printing footer."
msg -f "${@}"
else
return 1
fi
}
################################################################################
# Lists supported API models. #
# #
# Returns: #
# get_models() return code (See get_models()). #
################################################################################
list_models() {
local from=list_models
log -i "Listing supported API models."
get_models
local response_code=${?}
log -df "${from}" "API_RESPONSE_CODE=${response_code}"
if [[ ${response_code} -eq 0 ]]; then
if [[ ${JSON_RESPONSE} ]]; then
log -df "${from}" "Creating JSON response."
jq \
-nr \
--argjson API_MESSAGE "${API_MESSAGE}" \
'$API_MESSAGE | sort_by(.name)'
elif [[ ${MAIN_ACTION} == LIST_MODELS_WITH_LIST ]]; then
log -df "${from}" "Creating list response."
jq \
-nr \
--argjson API_MESSAGE "${API_MESSAGE}" \
'$API_MESSAGE | sort_by(.name) | .[].name | sub("models/"; "")'
else
log -df "${from}" "Creating formatted response."
msg "$(jq \
-nr \
--argjson API_MESSAGE "${API_MESSAGE}" \
'"# Supported API models" + "\n", ($API_MESSAGE | sort_by(.name) | .[] | "## " + .displayName + " (`" + (.name | sub("models/"; "")) + "`)", (.description // "No description") + "\n")')"
fi
else
case "${response_code}" in
3) api_error ;;
4) invalid_response ;;
*) log -e "${API_MESSAGE}" ;;
esac
return "${response_code}"
fi
}
################################################################################
# Sets or gets the system clipboard contents. #
# #
# Args: #
# Optional text to set to the system clipboard. #
# Sets: #
# CLIPBOARD - The contents of the system clipboard. #
# Returns: #
# 1 - No clipboard commands found. #
################################################################################
clipboard() {
local from=clipboard
if [[ ${*} ]]; then
log -i "Getting clipboard contents."
else
log -i "Copying contents to clipboard."
fi
CLIPBOARD=
if [[ "${DISPLAY}" ]]; then
if command -v xclip &>/dev/null; then
if [[ ${*} ]]; then
log -df "${from}" "Setting clipboard with xclip."
printf %s "${*}" | xclip -in -selection clipboard
else
log -df "${from}" "Getting clipboard with xclip."
CLIPBOARD=$(xclip -out -selection clipboard)
fi
elif command -v xsel &>/dev/null; then
if [[ ${*} ]]; then
log -df "${from}" "Setting clipboard with xsel."
printf %s "${*}" | xsel --clipboard --input
else
log -df "${from}" "Getting clipboard with xsel."
CLIPBOARD=$(xsel --clipboard --output)
fi
fi
elif command -v termux-api-start &>/dev/null; then
if [[ ${*} ]]; then
log -df "${from}" "Setting clipboard with termux-clipboard-set."
printf %s "${*}" | termux-clipboard-set
else
log -df "${from}" "Getting clipboard with termux-clipboard-get."
CLIPBOARD=$(termux-clipboard-get)
fi
else
return 1
fi
}
################################################################################
# Prints version information. #
################################################################################
print_version() {
echo "${NAME} version ${VERSION}"
echo "Copyright (C) 2025 ${AUTHOR} <${GITHUB}>."
echo "License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>."
echo
echo "This is free software, you are free to change and redistribute it."
echo "There is NO WARRANTY, to the extent permitted by law."
}
################################################################################
# Prints help information. #
################################################################################
print_help() {
echo "USAGE: ${NAME} [OPTIONS] [PROMPT]"
echo
echo "Commandline AI assistant."
echo
echo "OPTIONS"
echo " -S Save API key to file (${GEMINI_API_KEY_FILE//${HOME}/\~})."
echo " -m NAME Set API model."
echo " -i Force interactive mode (default when no PROMPT)."
echo " -c Print current chat."
echo " -n Backup current chat and create new chat."
echo " -N Like -n but doesn't backup current chat."
echo " -p Start private chat (never write chat history)."
echo " -d Disable chat history."
echo " -s Print separator betweeen chats."
echo " -r Prefer raw output (no pretty printing)."
echo " -R Disable commands (interactive mode only)."
echo " -j Prefer JSON output."
echo " -q Quiet mode (hide startup messages)."
echo " -Q Alias for -rq (raw output + quiet)."
echo " -l List supported models."
echo " -L INT Set log level (0 to 5)."
echo " -x Retry on connection error. Use Ctrl+C to stop."
echo " -v Print version information and exit."
echo " -h Print help information and exit."
echo
echo "ENVIRONMENT VARIABLES"
echo " GEMINI_API_KEY - The API key to use."
echo
echo "LEARN MORE"
echo " ${GITHUB}/${REPOSITORY}"
}
################################################################################
# Starts an animation (it's a bit buggy, only run one at a time) #
# #
# Sets Global variables: #
# ANIM_PID #
# Args: #
# OPTIONS (see case inside) #
# Prefix message #
################################################################################
animation() {
local frames=(' ' '. ' '.. ' '...')
local interval=0.1
local start=1
while getopts ":s" opt; do
case "${opt}" in
s)
start=
continue
;;
*) ;;