-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patholiveowl
More file actions
executable file
·2255 lines (1953 loc) · 84.4 KB
/
oliveowl
File metadata and controls
executable file
·2255 lines (1953 loc) · 84.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
#!/bin/bash
# oliveowl - Terminal AI Chat Assistant
# --- Configuration ---
CONFIG_DIR="$HOME/.config/oliveowl"
ENV_FILE="$CONFIG_DIR/.env"
HISTORY_DIR="$CONFIG_DIR/history"
CONFIG_FILE="$CONFIG_DIR/config"
PROMPT_HISTORY_FILE="$CONFIG_DIR/prompt_history.txt"
MAX_PROMPT_HISTORY=50
# --- Dependency Checks ---
check_dependency() {
if ! command -v "$1" &>/dev/null; then
echo "Error: Required command '$1' not found. Please install it." >&2
exit 1
fi
}
check_clipboard_tool() {
# Try wl-copy first: check if command exists AND if it runs without error (e.g., connects to Wayland)
if command -v wl-copy &>/dev/null && printf '' | wl-copy &>/dev/null; then
CLIPBOARD_TOOL="wl-copy"
echo "Using clipboard tool: wl-copy" # Optional: for debugging
# If wl-copy fails or isn't present, try xclip
elif command -v xclip &>/dev/null; then
CLIPBOARD_TOOL="xclip -selection clipboard"
echo "Using clipboard tool: xclip" # Optional: for debugging
else
# Error: Neither working wl-copy nor xclip found
echo "Error: No functional clipboard tool found (need working 'wl-copy' for Wayland or 'xclip' for X11)." >&2
exit 1
fi
# The debug echo is now inside the if/elif blocks
}
check_dependency "curl"
check_dependency "jq"
check_dependency "fzf"
check_dependency "bat"
check_dependency "gum" # Added gum dependency check
check_clipboard_tool # Sets $CLIPBOARD_TOOL
# --- Initial Setup ---
setup_config() {
mkdir -p "$CONFIG_DIR"
mkdir -p "$HISTORY_DIR"
# Create prompt history file if it doesn't exist
if [ ! -f "$PROMPT_HISTORY_FILE" ]; then
touch "$PROMPT_HISTORY_FILE"
fi
if [ ! -f "$ENV_FILE" ]; then
echo "Creating initial config file: $ENV_FILE"
echo "# Add your API keys here" >"$ENV_FILE"
echo "GEMINI_API_KEY=" >>"$ENV_FILE"
echo "OPENROUTER_API_KEY=" >>"$ENV_FILE"
echo "OPENAI_API_KEY=" >>"$ENV_FILE"
echo "CEREBRAS_API_KEY=" >>"$ENV_FILE"
echo "# Ollama base URL (e.g., http://localhost:11434)" >>"$ENV_FILE"
echo "OLLAMA_BASE_URL=" >>"$ENV_FILE"
echo "# Custom OpenAI-compatible providers" >>"$ENV_FILE"
echo "# Format: CUSTOM_PROVIDER_<PROVIDER_NAME>_URL=https://api.example.com/v1" >>"$ENV_FILE"
echo "# Format: CUSTOM_PROVIDER_<PROVIDER_NAME>_KEY=your_api_key" >>"$ENV_FILE"
echo "# Example:" >>"$ENV_FILE"
echo "# CUSTOM_PROVIDER_MYPROVIDER_URL=https://api.openai.com/v1" >>"$ENV_FILE"
echo "# CUSTOM_PROVIDER_MYPROVIDER_KEY=your_api_key" >>"$ENV_FILE"
chmod 600 "$ENV_FILE" # Secure the file
echo "Please edit $ENV_FILE and add your API keys and/or Ollama URL."
# Optionally exit here or prompt user
fi
# Load environment variables
set -a # Automatically export all variables
# Check if ENV_FILE exists before sourcing
if [ -f "$ENV_FILE" ]; then
source "$ENV_FILE"
else
echo "Warning: Environment file $ENV_FILE not found." >&2
fi
set +a
# Check if keys are set (basic check)
if [ -z "$GEMINI_API_KEY" ] && [ -z "$OPENROUTER_API_KEY" ] && [ -z "$OPENAI_API_KEY" ] && [ -z "$CEREBRAS_API_KEY" ] && [ -z "$OLLAMA_BASE_URL" ] && ! grep -q "^CUSTOM_PROVIDER_" "$ENV_FILE"; then
echo "Warning: No API keys (Gemini, OpenRouter, OpenAI, Cerebras) or OLLAMA_BASE_URL or custom providers found in $ENV_FILE. Please configure at least one." >&2
# Decide if we should exit or continue
fi
# Load or create config file
if [ ! -f "$CONFIG_FILE" ]; then
echo "Creating default settings file: $CONFIG_FILE"
echo "API_PROVIDER=" >"$CONFIG_FILE" # Will be 'gemini' or 'openrouter'
echo "MODEL=" >>"$CONFIG_FILE"
echo "EDITOR=\"vi\"" >>"$CONFIG_FILE" # Add default editor
fi
# Load config settings
# Check if CONFIG_FILE exists before sourcing
if [ -f "$CONFIG_FILE" ]; then
source "$CONFIG_FILE"
else
echo "Warning: Config file $CONFIG_FILE not found. Using defaults." >&2
fi
# Set default editor if not found in config
EDITOR="${EDITOR:-vi}"
# NOTE: Configuration completeness check moved to main()
# Ensure EDITOR command exists - Moved to after setup_config call before main()
}
# --- Configuration Function ---
fetch_openrouter_models() {
local models_json
echo "Fetching models from OpenRouter..." >&2
models_json=$(curl -s https://openrouter.ai/api/v1/models)
if [ $? -ne 0 ] || [ -z "$models_json" ]; then
echo "Error: Failed to fetch models from OpenRouter." >&2
return 1
fi
# Extract model IDs, filter out duplicates, sort
echo "$models_json" | jq -r '.data[].id' | sort -u
}
fetch_openai_models() {
if [ -z "$OPENAI_API_KEY" ]; then
echo "Error: OPENAI_API_KEY not set in $ENV_FILE. Cannot fetch models." >&2
return 1
fi
local models_json
echo "Fetching models from OpenAI..." >&2
models_json=$(curl -s -H "Authorization: Bearer $OPENAI_API_KEY" https://api.openai.com/v1/models)
if [ $? -ne 0 ] || [ -z "$models_json" ]; then
echo "Error: Failed to fetch models from OpenAI." >&2
return 1
fi
# Check for API errors
local openai_error=$(echo "$models_json" | jq -r '.error.message // empty')
if [ -n "$openai_error" ]; then
echo "Warning: OpenAI API Error when fetching models: $openai_error" >&2
return 1
fi
# Check if data array exists (like OpenAI)
if ! echo "$models_json" | jq -e '.data | type == "array"' >/dev/null 2>&1; then
echo "Warning: Invalid JSON or missing 'data' array in OpenAI models response." >&2
# echo "OpenAI response: $models_json" >&2 # For debugging
return 1
fi
# Extract model IDs, filter out duplicates, sort
local extracted_models
extracted_models=$(echo "$models_json" | jq -r '.data[].id // empty' | sort -u | grep .)
if [ -z "$extracted_models" ]; then
echo "Warning: No models found in OpenAI response or failed to parse names." >&2
return 1
fi
echo "$extracted_models"
return 0 # Success
}
fetch_cerebras_models() {
if [ -z "$CEREBRAS_API_KEY" ]; then
echo "Error: CEREBRAS_API_KEY not set in $ENV_FILE. Cannot fetch models." >&2
return 1
fi
local models_json
echo "Fetching models from Cerebras..." >&2
models_json=$(curl -s -H "Authorization: Bearer $CEREBRAS_API_KEY" https://api.cerebras.ai/v1/models)
if [ $? -ne 0 ] || [ -z "$models_json" ]; then
echo "Error: Failed to fetch models from Cerebras." >&2
return 1
fi
# Check for API errors
local cerebras_error=$(echo "$models_json" | jq -r '.error.message // empty')
if [ -n "$cerebras_error" ]; then
echo "Warning: Cerebras API Error when fetching models: $cerebras_error" >&2
return 1
fi
# Check if data array exists (like OpenAI)
if ! echo "$models_json" | jq -e '.data | type == "array"' >/dev/null 2>&1; then
echo "Warning: Invalid JSON or missing 'data' array in Cerebras models response." >&2
# echo "Cerebras response: $models_json" >&2 # For debugging
return 1
fi
# Extract model IDs, filter out duplicates, sort
local extracted_models
extracted_models=$(echo "$models_json" | jq -r '.data[].id // empty' | sort -u | grep .)
if [ -z "$extracted_models" ]; then
echo "Warning: No models found in Cerebras response or failed to parse names." >&2
return 1
fi
echo "$extracted_models"
return 0 # Success
}
# Function to fetch models from a local Ollama instance
fetch_ollama_models() {
local ollama_url_base="${OLLAMA_BASE_URL:-http://localhost:11434}"
# Remove trailing slash if present
ollama_url_base=$(echo "$ollama_url_base" | sed 's:/*$::')
local models_api_url="${ollama_url_base}/api/tags"
local models_json
echo "Fetching models from Ollama at $ollama_url_base..." >&2
# Timeout curl after 5 seconds for local requests to avoid long hangs
models_json=$(curl --connect-timeout 5 -s "$models_api_url")
if [ $? -ne 0 ]; then
echo "Warning: curl command failed for Ollama. Is Ollama running and accessible at $ollama_url_base?" >&2
return 1
fi
if [ -z "$models_json" ]; then
echo "Warning: Received empty response from Ollama models API." >&2
return 1
fi
# Check for Ollama API errors (e.g., if the endpoint exists but returns an error object)
local ollama_error=$(echo "$models_json" | jq -r '.error // empty')
if [ -n "$ollama_error" ]; then
echo "Warning: Ollama API Error when fetching models: $ollama_error" >&2
return 1
fi
# Check if the 'models' array exists and is an array
if ! echo "$models_json" | jq -e '.models | type == "array"' >/dev/null 2>&1; then
echo "Warning: Invalid JSON or missing 'models' array in Ollama response." >&2
# echo "Ollama response: $models_json" >&2 # For debugging
return 1
fi
# Extract model names, filter out duplicates, sort
local extracted_models
extracted_models=$(echo "$models_json" | jq -r '.models[].name // empty' | sort -u | grep .) # grep . to remove empty lines if any
if [ -z "$extracted_models" ]; then
echo "Warning: No models found in Ollama response or failed to parse names." >&2
return 1 # Indicate no models found or parse error
fi
echo "$extracted_models"
return 0 # Success
}
configure_settings() {
echo "--- OliveOwl Configuration ---"
# 1. Select Configuration Option
local config_options="Change Model\nAdd Provider\nChange Editor\nEdit Instructions"
local selected_option=$(echo -e "$config_options" | fzf --prompt="Select Configuration Option: " --height=5 --layout=reverse)
if [ -z "$selected_option" ]; then
echo "Configuration cancelled."
return 1
fi
# Handle Add Provider option
if [[ "$selected_option" == "Add Provider" ]]; then
add_provider
# After adding provider, return to continue with previous flow
return 0
elif [[ "$selected_option" == "Change Editor" ]]; then
# Handle Change Editor option
local current_editor=${EDITOR:-vi}
local new_editor
new_editor=$(gum input --header "Configure Editor" --placeholder "Enter preferred editor command (current: $current_editor)..." --value "$current_editor")
if [ $? -eq 0 ] && [ -n "$new_editor" ]; then
EDITOR="$new_editor"
fi
# Save editor configuration
echo "Saving editor configuration..."
if [ -f "$CONFIG_FILE" ]; then
# Update existing config file with new editor
sed -i "s|^EDITOR=.*|EDITOR=\"$EDITOR\"|" "$CONFIG_FILE"
else
# Create new config file with editor setting
echo "API_PROVIDER=\"$API_PROVIDER\"" >"$CONFIG_FILE"
echo "MODEL=\"$MODEL\"" >>"$CONFIG_FILE"
echo "EDITOR=\"$EDITOR\"" >>"$CONFIG_FILE"
fi
echo "Editor configuration saved."
return 0
elif [[ "$selected_option" == "Edit Instructions" ]]; then
# Handle Edit Instructions option
local instructions_file="$CONFIG_DIR/extra_instructions.txt"
"$EDITOR" "$instructions_file"
echo "Instructions saved."
return 0
fi
# 2. Select API Provider (for Change Model or Add Provider paths)
local providers="Gemini\nOpenRouter\nOpenAI\nOllama\nCerebras"
# Add custom providers to the list
while IFS= read -r line; do
if [[ "$line" =~ ^CUSTOM_PROVIDER_([A-Z0-9_]+)_URL= ]]; then
provider_name="${BASH_REMATCH[1]}"
providers="$providers\n$provider_name"
fi
done < "$ENV_FILE"
API_PROVIDER=$(echo -e "$providers" | fzf --prompt="Select API Provider: " --height=7 --layout=reverse)
if [ -z "$API_PROVIDER" ]; then
echo "Configuration cancelled."
return 1
fi
# Check if API key exists for selected provider and prompt to add if missing
local api_key_exists=true
case "$API_PROVIDER" in
"Gemini")
if [ -z "$GEMINI_API_KEY" ]; then
api_key_exists=false
fi
;;
"OpenRouter")
if [ -z "$OPENROUTER_API_KEY" ]; then
api_key_exists=false
fi
;;
"OpenAI")
if [ -z "$OPENAI_API_KEY" ]; then
api_key_exists=false
fi
;;
"Cerebras")
if [ -z "$CEREBRAS_API_KEY" ]; then
api_key_exists=false
fi
;;
"Ollama")
# For Ollama, check if URL is set
if [ -z "$OLLAMA_BASE_URL" ]; then
api_key_exists=false
fi
;;
*)
# Check if it's a custom provider
if [[ "$API_PROVIDER" =~ ^[A-Z0-9_]+$ ]]; then
local provider_url_var="CUSTOM_PROVIDER_${API_PROVIDER}_URL"
local provider_key_var="CUSTOM_PROVIDER_${API_PROVIDER}_KEY"
if [ -z "${!provider_url_var}" ] || [ -z "${!provider_key_var}" ]; then
api_key_exists=false
fi
fi
;;
esac
if [ "$api_key_exists" = false ]; then
echo "API key/URL not found for $API_PROVIDER."
local add_key_choice
add_key_choice=$(gum choose --header "Add $API_PROVIDER configuration?" "Yes" "No")
if [ "$add_key_choice" = "Yes" ]; then
if [[ "$API_PROVIDER" =~ ^[A-Z0-9_]+$ ]]; then
# It's a custom provider, need to add it
add_custom_provider
else
add_provider_key "$API_PROVIDER"
fi
# Reload environment variables
set -a
if [ -f "$ENV_FILE" ]; then
source "$ENV_FILE"
fi
set +a
else
# If user chooses not to add key, continue but warn them
echo "Warning: You may not be able to use $API_PROVIDER without configuration."
fi
fi
# 2. Select Model
local model_list=""
local fetched_models=""
local fzf_input=""
local manual_entry_option="-- Manual Model Entry --"
case "$API_PROVIDER" in
"Gemini")
# Check for Gemini Key first
if [ -z "$GEMINI_API_KEY" ]; then
echo "Warning: GEMINI_API_KEY not set in $ENV_FILE. Cannot fetch models." >&2
# Proceed with only manual entry option
else
echo "Fetching Gemini models..."
local gemini_url="https://generativelanguage.googleapis.com/v1beta/models?key=$GEMINI_API_KEY"
local gemini_response=$(curl -s "$gemini_url")
if [ $? -ne 0 ]; then
echo "Warning: curl command failed for Gemini. Using manual entry only." >&2
else
local gemini_error=$(echo "$gemini_response" | jq -r '.error.message // empty')
if [ -n "$gemini_error" ]; then
echo "Warning: Gemini API Error: $gemini_error. Using manual entry only." >&2
elif echo "$gemini_response" | jq -e '.models' >/dev/null 2>&1; then
fetched_models=$(echo "$gemini_response" | jq -r '.models[].name')
if [ -z "$fetched_models" ]; then
echo "Warning: No models found in Gemini response. Using manual entry only." >&2
fi
else
echo "Warning: Invalid JSON or missing 'models' in Gemini response. Using manual entry only." >&2
fi
fi
fi
;;
"OpenRouter")
# OpenRouter key not strictly needed for model listing, but good practice to have it set for actual use later
if [ -z "$OPENROUTER_API_KEY" ]; then
echo "Warning: OPENROUTER_API_KEY not set in $ENV_FILE. You will need it to use OpenRouter models." >&2
# Continue fetching anyway, as the endpoint is public
fi
# The fetch_openrouter_models function handles its own "Fetching..." message and errors.
fetched_models=$(fetch_openrouter_models)
if [ $? -ne 0 ] || [ -z "$fetched_models" ]; then
# fetch_openrouter_models already prints detailed errors to stderr.
# This message just confirms fallback to manual entry.
echo "Warning: Using manual entry for OpenRouter models due to fetch error or no models found." >&2
fetched_models="" # Ensure it's empty so the manual entry path is taken later
fi
;;
"OpenAI")
# The fetch_openai_models function handles its own "Fetching..." message and errors.
fetched_models=$(fetch_openai_models)
if [ $? -ne 0 ] || [ -z "$fetched_models" ]; then
# fetch_openai_models already prints detailed errors to stderr.
echo "Warning: Using manual entry for OpenAI models due to fetch error or no models found." >&2
fetched_models="" # Ensure it's empty so the manual entry path is taken later
else
echo "Successfully fetched OpenAI models." >&2
fi
;;
"Cerebras")
# The fetch_cerebras_models function handles its own "Fetching..." message and errors.
fetched_models=$(fetch_cerebras_models)
if [ $? -ne 0 ] || [ -z "$fetched_models" ]; then
# fetch_cerebras_models already prints detailed errors to stderr.
echo "Warning: Using manual entry for Cerebras models due to fetch error or no models found." >&2
fetched_models="" # Ensure it's empty so the manual entry path is taken later
else
echo "Successfully fetched Cerebras models." >&2
fi
;;
"Ollama")
# OLLAMA_BASE_URL from .env will be used by call_api and fetch_ollama_models.
# Check if OLLAMA_BASE_URL is set, if not, fetching will use default.
if [ -z "$OLLAMA_BASE_URL" ]; then
echo "Info: OLLAMA_BASE_URL not set in $ENV_FILE. Will attempt to fetch models from default http://localhost:11434." >&2
fi
fetched_ollama_models=$(fetch_ollama_models)
if [ $? -eq 0 ] && [ -n "$fetched_ollama_models" ]; then
fetched_models="$fetched_ollama_models"
echo "Successfully fetched Ollama models." >&2
else
echo "Warning: Could not fetch Ollama models. Using manual entry only." >&2
fetched_models="" # Ensure it's empty on failure
fi
;;
*)
# Check if it's a custom provider
if [[ "$API_PROVIDER" =~ ^[A-Z0-9_]+$ ]]; then
local provider_url_var="CUSTOM_PROVIDER_${API_PROVIDER}_URL"
local provider_key_var="CUSTOM_PROVIDER_${API_PROVIDER}_KEY"
if [ -n "${!provider_url_var}" ] && [ -n "${!provider_key_var}" ]; then
fetched_custom_models=$(fetch_custom_models "$API_PROVIDER")
if [ $? -eq 0 ] && [ -n "$fetched_custom_models" ]; then
fetched_models="$fetched_custom_models"
echo "Successfully fetched models from $API_PROVIDER." >&2
else
echo "Warning: Could not fetch models from $API_PROVIDER. Using manual entry only." >&2
fetched_models="" # Ensure it's empty on failure
fi
else
echo "Warning: Custom provider $API_PROVIDER not properly configured. Using manual entry only." >&2
fetched_models=""
fi
else
echo "Invalid provider selected."
exit 1
fi
;;
esac
# Prepare input for fzf: Manual option first, then fetched models
fzf_input="$manual_entry_option"
if [ -n "$fetched_models" ]; then
# Sort models alphabetically for better usability
fetched_models=$(echo "$fetched_models" | sort)
fzf_input="$fzf_input\n$fetched_models"
fi
# Use fzf for selection
MODEL=$(echo -e "$fzf_input" | fzf --prompt="Select Model for $API_PROVIDER: " --height=15 --layout=reverse)
# Handle fzf cancellation
if [ -z "$MODEL" ]; then
echo "Configuration cancelled."
return 1
fi
# Check if manual entry was selected
if [[ "$MODEL" == "$manual_entry_option" ]]; then
echo "Manual entry selected."
MODEL=$(gum input --placeholder "Enter exact model name/ID for $API_PROVIDER...")
# Handle cancellation of gum input
if [ $? -ne 0 ] || [ -z "$MODEL" ]; then
echo "Manual entry cancelled or empty. Configuration cancelled."
return 1
fi
fi
# MODEL variable now holds either the selected fetched model or the manually entered one
# 3. Configure Editor
local current_editor=${EDITOR:-vi} # Get current or default from sourced config or default
local new_editor
new_editor=$(gum input --header "Configure Editor" --placeholder "Enter preferred editor command (current: $current_editor)..." --value "$current_editor")
# Update EDITOR only if gum input succeeded and value is not empty
if [ $? -eq 0 ] && [ -n "$new_editor" ]; then
EDITOR="$new_editor"
fi
# 4. Save Configuration
echo "Saving configuration..."
if [ -f "$CONFIG_FILE" ]; then
# Update existing config file
sed -i "s|^API_PROVIDER=.*|API_PROVIDER=\"$API_PROVIDER\"|" "$CONFIG_FILE"
sed -i "s|^MODEL=.*|MODEL=\"$MODEL\"|" "$CONFIG_FILE"
# Only update editor if it doesn't exist or is empty
if ! grep -q "^EDITOR=" "$CONFIG_FILE" || [ -z "$(grep "^EDITOR=" "$CONFIG_FILE" | cut -d'=' -f2)" ]; then
echo "EDITOR=\"$EDITOR\"" >>"$CONFIG_FILE"
fi
else
# Create new config file
echo "API_PROVIDER=\"$API_PROVIDER\"" >"$CONFIG_FILE"
echo "MODEL=\"$MODEL\"" >>"$CONFIG_FILE"
echo "EDITOR=\"$EDITOR\"" >>"$CONFIG_FILE"
fi
echo "Configuration saved to $CONFIG_FILE:"
echo " Provider: $API_PROVIDER"
echo " Model: $MODEL"
echo " Editor: $EDITOR"
echo "Setup complete. You can now run '$0'." # Use $0 for the current script name
}
# --- Prompt History Functions ---
# Save a prompt to history
save_prompt_to_history() {
local prompt="$1"
if [ -n "$prompt" ]; then
# Add to history file
echo "$prompt" >> "$PROMPT_HISTORY_FILE"
# Keep only the last MAX_PROMPT_HISTORY entries
if [ -f "$PROMPT_HISTORY_FILE" ]; then
tail -n "$MAX_PROMPT_HISTORY" "$PROMPT_HISTORY_FILE" > "$PROMPT_HISTORY_FILE.tmp"
mv "$PROMPT_HISTORY_FILE.tmp" "$PROMPT_HISTORY_FILE"
fi
fi
}
# --- Provider Management Functions ---
# Add a new API provider and key
add_provider() {
while true; do
echo "Add Provider selected."
# Select provider
local providers="Gemini\nOpenRouter\nOpenAI\nCerebras\nOllama\nCustom OpenAI-Compatible"
local selected_provider=$(echo -e "$providers" | fzf --prompt="Select Provider to Add: " --height=7 --layout=reverse)
if [ -z "$selected_provider" ]; then
echo "Provider selection cancelled."
break
fi
if [[ "$selected_provider" == "Custom OpenAI-Compatible" ]]; then
add_custom_provider
else
add_provider_key "$selected_provider"
fi
# Ask if user wants to add another provider
echo ""
local add_another
add_another=$(gum choose --header "Add another provider?" "Yes" "No")
if [ "$add_another" != "Yes" ]; then
break
fi
done
# Reload environment variables
set -a
if [ -f "$ENV_FILE" ]; then
source "$ENV_FILE"
fi
set +a
return 0
}
# Add API key or URL for a specific provider
add_provider_key() {
local selected_provider="$1"
local api_key=""
local env_var_name=""
# Handle Ollama differently (URL instead of API key)
if [[ "$selected_provider" == "Ollama" ]]; then
local ollama_url
ollama_url=$(gum input --header "Ollama Configuration" --placeholder "Enter Ollama base URL (e.g., http://localhost:11434)...")
if [ $? -eq 0 ] && [ -n "$ollama_url" ]; then
# Update .env file with OLLAMA_BASE_URL
if [ -f "$ENV_FILE" ]; then
# Check if OLLAMA_BASE_URL already exists
if grep -q "^OLLAMA_BASE_URL=" "$ENV_FILE"; then
# Update existing OLLAMA_BASE_URL
sed -i "s|^OLLAMA_BASE_URL=.*|OLLAMA_BASE_URL=$ollama_url|" "$ENV_FILE"
else
# Add new OLLAMA_BASE_URL
echo "OLLAMA_BASE_URL=$ollama_url" >>"$ENV_FILE"
fi
else
# Create new .env file
echo "# Add your API keys here" >"$ENV_FILE"
echo "GEMINI_API_KEY=" >>"$ENV_FILE"
echo "OPENROUTER_API_KEY=" >>"$ENV_FILE"
echo "OPENAI_API_KEY=" >>"$ENV_FILE"
echo "CEREBRAS_API_KEY=" >>"$ENV_FILE"
echo "OLLAMA_BASE_URL=$ollama_url" >>"$ENV_FILE"
chmod 600 "$ENV_FILE"
fi
echo "Ollama URL saved to $ENV_FILE"
return 0
else
echo "Ollama configuration cancelled."
return 1
fi
else
# Handle other providers (API keys)
case "$selected_provider" in
"Gemini") env_var_name="GEMINI_API_KEY" ;;
"OpenRouter") env_var_name="OPENROUTER_API_KEY" ;;
"OpenAI") env_var_name="OPENAI_API_KEY" ;;
"Cerebras") env_var_name="CEREBRAS_API_KEY" ;;
esac
# Input API key securely
api_key=$(gum input --header "$selected_provider API Key" --placeholder "Enter your $selected_provider API key..." --password)
if [ $? -eq 0 ] && [ -n "$api_key" ]; then
# Update .env file with API key
if [ -f "$ENV_FILE" ]; then
# Check if the API key variable already exists
if grep -q "^$env_var_name=" "$ENV_FILE"; then
# Update existing API key
sed -i "s|^$env_var_name=.*|$env_var_name=$api_key|" "$ENV_FILE"
else
# Add new API key
echo "$env_var_name=$api_key" >>"$ENV_FILE"
fi
else
# Create new .env file
echo "# Add your API keys here" >"$ENV_FILE"
echo "GEMINI_API_KEY=" >>"$ENV_FILE"
echo "OPENROUTER_API_KEY=" >>"$ENV_FILE"
echo "OPENAI_API_KEY=" >>"$ENV_FILE"
echo "CEREBRAS_API_KEY=" >>"$ENV_FILE"
echo "OLLAMA_BASE_URL=" >>"$ENV_FILE"
echo "$env_var_name=$api_key" >>"$ENV_FILE"
chmod 600 "$ENV_FILE"
fi
echo "$selected_provider API key saved to $ENV_FILE"
return 0
else
echo "API key input cancelled."
return 1
fi
fi
}
# Add a custom OpenAI-compatible provider
add_custom_provider() {
echo "Add Custom OpenAI-Compatible Provider selected."
# Get provider name
local provider_name
provider_name=$(gum input --header "Provider Configuration" --placeholder "Enter provider name (e.g., ZAI, MYPROVIDER)...")
if [ $? -ne 0 ] || [ -z "$provider_name" ]; then
echo "Provider name input cancelled."
return 1
fi
# Convert to uppercase for consistency
provider_name=$(echo "$provider_name" | tr '[:lower:]' '[:upper:]')
# Check if provider already exists
local provider_url_var="CUSTOM_PROVIDER_${provider_name}_URL"
local provider_key_var="CUSTOM_PROVIDER_${provider_name}_KEY"
if [ -f "$ENV_FILE" ] && (grep -q "^$provider_url_var=" "$ENV_FILE" || grep -q "^$provider_key_var=" "$ENV_FILE"); then
echo "Provider $provider_name already exists. Use /config to change model or update manually."
return 1
fi
# Get base URL
local base_url
base_url=$(gum input --header "Provider Configuration" --placeholder "Enter base URL (e.g., https://api.openai.com/v1)...")
if [ $? -ne 0 ] || [ -z "$base_url" ]; then
echo "Base URL input cancelled."
return 1
fi
# Remove trailing slash if present
base_url=$(echo "$base_url" | sed 's:/*$::')
# Get API key
local api_key
api_key=$(gum input --header "Provider Configuration" --placeholder "Enter API key..." --password)
if [ $? -ne 0 ] || [ -z "$api_key" ]; then
echo "API key input cancelled."
return 1
fi
# Update .env file
if [ -f "$ENV_FILE" ]; then
echo "CUSTOM_PROVIDER_${provider_name}_URL=$base_url" >>"$ENV_FILE"
echo "CUSTOM_PROVIDER_${provider_name}_KEY=$api_key" >>"$ENV_FILE"
else
echo "# Add your API keys here" >"$ENV_FILE"
echo "GEMINI_API_KEY=" >>"$ENV_FILE"
echo "OPENROUTER_API_KEY=" >>"$ENV_FILE"
echo "OPENAI_API_KEY=" >>"$ENV_FILE"
echo "CEREBRAS_API_KEY=" >>"$ENV_FILE"
echo "OLLAMA_BASE_URL=" >>"$ENV_FILE"
echo "CUSTOM_PROVIDER_${provider_name}_URL=$base_url" >>"$ENV_FILE"
echo "CUSTOM_PROVIDER_${provider_name}_KEY=$api_key" >>"$ENV_FILE"
chmod 600 "$ENV_FILE"
fi
echo "Custom provider $provider_name saved to $ENV_FILE"
return 0
}
# Fetch models from a custom OpenAI-compatible provider
fetch_custom_models() {
local provider_name="$1"
local provider_url_var="CUSTOM_PROVIDER_${provider_name}_URL"
local provider_key_var="CUSTOM_PROVIDER_${provider_name}_KEY"
local base_url="${!provider_url_var}"
local api_key="${!provider_key_var}"
if [ -z "$base_url" ] || [ -z "$api_key" ]; then
echo "Error: Provider $provider_name not properly configured." >&2
return 1
fi
local models_api_url="${base_url}/models"
local models_json
echo "Fetching models from $provider_name at $base_url..." >&2
models_json=$(curl -s -H "Authorization: Bearer $api_key" "$models_api_url")
if [ $? -ne 0 ] || [ -z "$models_json" ]; then
echo "Error: Failed to fetch models from $provider_name." >&2
return 1
fi
# Check for API errors
local custom_error=$(echo "$models_json" | jq -r '.error.message // empty')
if [ -n "$custom_error" ]; then
echo "Warning: $provider_name API Error when fetching models: $custom_error" >&2
return 1
fi
# Check if data array exists
if ! echo "$models_json" | jq -e '.data | type == "array"' >/dev/null 2>&1; then
echo "Warning: Invalid JSON or missing 'data' array in $provider_name models response." >&2
return 1
fi
# Extract model IDs, filter out duplicates, sort
local extracted_models
extracted_models=$(echo "$models_json" | jq -r '.data[].id // empty' | sort -u | grep .)
if [ -z "$extracted_models" ]; then
echo "Warning: No models found in $provider_name response or failed to parse names." >&2
return 1
fi
echo "$extracted_models"
return 0
}
# Get previous prompt by index (1 = most recent)
get_previous_prompt() {
local index=$1
if [ -f "$PROMPT_HISTORY_FILE" ] && [ "$index" -gt 0 ]; then
tail -n "$index" "$PROMPT_HISTORY_FILE" | head -n 1
fi
}
# Display prompt history and let user select
select_from_prompt_history() {
if [ ! -f "$PROMPT_HISTORY_FILE" ] || [ ! -s "$PROMPT_HISTORY_FILE" ]; then
echo "No prompt history available."
return 1
fi
# Create a numbered list of recent prompts
local history_items=()
local count=0
while IFS= read -r line; do
if [ -n "$line" ]; then
history_items+=("$line")
count=$((count + 1))
fi
done < <(tail -n "$MAX_PROMPT_HISTORY" "$PROMPT_HISTORY_FILE" | tac)
if [ ${#history_items[@]} -eq 0 ]; then
echo "No prompt history available."
return 1
fi
# Use gum choose to let user select from history
local selected
selected=$(printf '%s\n' "${history_items[@]}" | gum choose --header "Select a previous prompt (or press Esc to cancel):")
local gum_status=$?
if [ $gum_status -eq 0 ] && [ -n "$selected" ]; then
echo "$selected"
return 0
else
return 1
fi
}
# Display help information
show_help() {
echo "OliveOwl Commands:"
echo " /exit, /quit, /q - Exit the application"
echo " /history, /h - Load previous chat sessions"
echo " /config, /c - Complete configuration (API + editor + other settings)"
echo " /view, /v - View current chat in editor"
echo " /new, /n - Start a new chat session"
echo " /prompt-history, /ph, /p - Select from previous prompts"
echo " /help, /? - Show this help message"
echo ""
echo "All commands must be the only text in your input to be recognized."
}
# --- System Prompt ---
# Instructs the AI on formatting and behavior
load_system_prompt() {
local base_prompt=$(cat <<'EOF'
You are a helpful AI assistant. Answer user questions clearly and concisely.
For regular questions, respond in natural language without using code blocks.
ONLY use Markdown code blocks when providing code, commands, scripts, or any content that users might need to copy and paste. This includes:
- Shell commands (bash, zsh, fish)
- Programming code (Python, JavaScript, etc.)
- Configuration files
- Docker commands
- Git commands
- Ollama commands
- Game commands (Minecraft, etc.)
- HTML/CSS/SQL or other markup/query languages
When using code blocks, format them properly so they can be copied and used directly:
```bash
echo "example command"
```
For all other responses, use plain text without code blocks.
EOF
)
local instructions_file="$CONFIG_DIR/extra_instructions.txt"
if [ -f "$instructions_file" ] && [ -s "$instructions_file" ]; then
local extra_instructions=$(cat "$instructions_file")
echo -e "$base_prompt\n\nAdditional Instructions:\n$extra_instructions"
else
echo "$base_prompt"
fi
}
SYSTEM_PROMPT=$(load_system_prompt)
# --- History Management ---
CHAT_HISTORY=() # In-memory array of JSON objects for the current session
CURRENT_HISTORY_FILE=""
CURRENT_SESSION_NAME=""
USER_PROMPT_COUNT=0
IS_MANUALLY_NAMED=false
# Function to create the API-specific JSON object string for a message
# Usage: create_api_message_json "role" "content"
# Returns a compact JSON string suitable for the configured API provider
create_api_message_json() {
local role="$1"
local content="$2"
# Content is passed directly, assuming it doesn't need pre-escaping for jq --arg
# json_content=$(echo "$content" | jq -Rsa .) # REMOVED
if [[ "$API_PROVIDER" == "Gemini" ]]; then
# Gemini uses "user" and "model" roles, and a "parts" array
local gemini_role="$role"
# Map OpenRouter's 'assistant' role if needed (though we primarily use 'model' for Gemini AI responses)
if [[ "$role" == "assistant" ]]; then
gemini_role="model"
fi
# Simple text part for now - Pass content directly to --arg text_content
# jq needs the value for "text" to be a valid JSON string. Let jq handle the encoding.
jq -n --arg role "$gemini_role" --arg text_content "$content" \
'{role: $role, parts: [{"text": $text_content}]}' | jq -c .
else # OpenRouter uses "user" and "assistant"
local openrouter_role="$role"
# Map Gemini's 'model' role if needed (though we primarily use 'assistant' for OpenRouter AI responses)
if [[ "$role" == "model" ]]; then
openrouter_role="assistant"
fi
# Pass content directly to --arg content
jq -n --arg role "$openrouter_role" --arg content "$content" \
'{role: $role, content: $content}' | jq -c .
fi
}
# Function to load history from a file into the CHAT_HISTORY array
# Usage: load_history "path/to/history.json"
load_history() {
local file_path="$1"
if [ ! -f "$file_path" ]; then
echo "History file not found: $file_path" >&2
return 1
fi
# Check if the file is valid JSON and contains the expected structure
if ! jq -e '(.session_name != null) and (.messages | type == "array")' "$file_path" >/dev/null 2>&1; then
echo "Error: History file is not in the new format or is corrupt: $file_path" >&2
# TODO: Offer to migrate old history file format? For now, we fail.
return 1
fi
# Load data from the new structure
CURRENT_SESSION_NAME=$(jq -r '.session_name' "$file_path")
mapfile -t CHAT_HISTORY < <(jq -c '.messages[]' "$file_path")
if [ $? -ne 0 ]; then
echo "Error: Failed to parse messages from history file: $file_path" >&2
CHAT_HISTORY=() # Clear history on parse error
return 1
fi
# Set session properties
CURRENT_HISTORY_FILE="$file_path"
# Heuristic: if filename doesn't start with chat_, it was manually named.
if [[ ! "$(basename "$file_path")" =~ ^chat_ ]]; then
IS_MANUALLY_NAMED=true
else
IS_MANUALLY_NAMED=false
fi
# Recalculate user prompt count from loaded history
USER_PROMPT_COUNT=0
for item_json in "${CHAT_HISTORY[@]}"; do
if [[ $(echo "$item_json" | jq -r '.message_json.role') == "user" ]]; then
((USER_PROMPT_COUNT++))
fi
done
echo "Loaded Session: $CURRENT_SESSION_NAME"
echo "History file: $CURRENT_HISTORY_FILE"
}
# Function to display the current CHAT_HISTORY
display_history() {
echo "--- Chat History for: $CURRENT_SESSION_NAME ---"
# Iterate through the CHAT_HISTORY array (each element is a JSON string object)
for history_item_json in "${CHAT_HISTORY[@]}"; do
# Parse the outer object to get message_json and model_used
local message_json model_used role content display_model_name
message_json=$(echo "$history_item_json" | jq -r '.message_json // empty')
model_used=$(echo "$history_item_json" | jq -r '.model_used // empty') # Will be empty for user messages
if [ -z "$message_json" ]; then