-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaudius.sh
More file actions
executable file
·2450 lines (2324 loc) · 93.7 KB
/
claudius.sh
File metadata and controls
executable file
·2450 lines (2324 loc) · 93.7 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
#!/usr/bin/env bash
# Claudius v0.9.15 - Claude Code multi-backend bootstrapper (LM Studio, Ollama, llama.cpp server, OpenRouter, Custom, NewAPI, NVIDIA API).
# Author: Lefteris Iliadis (Somnius) https://github.com/Somnius
# Check server, pick model, set context (where applicable), update config, run claude.
# Supports: bash, zsh, fish, ksh, sh. Platforms: Linux, macOS, Windows (Git Bash/WSL).
set -euo pipefail
VERSION="0.9.15"
# --help function: Display usage information
print_help() {
cat << 'EOF'
Usage: claudius [OPTIONS]
Claudius v0.9.15 - Claude Code multi-backend bootstrapper
Connects Claude Code (Anthropic's agentic CLI) to LM Studio, Ollama, llama.cpp server (llama-server),
OpenRouter, Custom (many presets), NewAPI (QuantumNous unified gateway), or NVIDIA API (NIM catalog on integrate.api.nvidia.com). Custom presets: Alibaba, Kimi,
DeepSeek, Groq, OpenRouter, xAI, OpenAI, or Other. NewAPI: self-host or cloud; chat at base/v1, list models at base/api/models.
Writes env vars to your shell config (bash/zsh/fish/ksh/sh).
Options:
--help, -h Show this help message and exit
--init Reset preferences and backend (show reply duration, keep session, which backend)
--purge Interactive menu to purge saved Claude Code session data
--dry-run Test flow without writing config or starting Claude
--test Alias for --dry-run
--by-pass-start Do not ask to start Claude Code after setup; exit once config is written (for use in scripts)
--last Use last base URL, model, and context length; skip model menu and start Claude Code
Environment Variables:
CLAUDIUS_BACKEND Backend: lmstudio | ollama | llamacpp | openrouter | custom | newapi | nvidia
LMSTUDIO_URL LM Studio base URL (default: http://localhost:1234)
OLLAMA_URL Ollama base URL (default: http://localhost:11434)
LLAMA_CPP_URL llama-server base URL (default: http://127.0.0.1:8080)
CLAUDIUS_AUTH_TOKEN Override ANTHROPIC_AUTH_TOKEN (e.g. for llamacpp; default from prefs or lmstudio)
CLAUDIUS_BASE_URL Override base URL (custom, openrouter, newapi, nvidia, or llamacpp)
CLAUDIUS_API_KEY API key in prefs; OpenRouter, NVIDIA API, and Alibaba DashScope …/apps/anthropic (custom) are written as ANTHROPIC_AUTH_TOKEN with ANTHROPIC_API_KEY "" (Claude Code /login workaround)
OPENROUTER_URL Default https://openrouter.ai/api (do not use .../api/v1 for Claude Code)
NVIDIA_URL NVIDIA API host (default: https://integrate.api.nvidia.com). Listing uses GET host/v1/models; chat requires Anthropic /v1/messages, which this host does not document — use a proxy or another backend for Claude Code chat.
CURL_TIMEOUT_CLOUD Max time (seconds) for OpenRouter/custom model-list HTTP; default 25 (default CURL_TIMEOUT is 10)
DASHSCOPE_INTL_ANTHROPIC_BASE / DASHSCOPE_INTL_OPENAI_BASE Override Alibaba intl. Anthropic vs OpenAI list URLs (advanced)
CLAUDIUS_SHELL Override shell for config file (bash|zsh|fish|ksh|sh)
Examples:
claudius # Run full flow: choose backend, model, start Claude
claudius --init # Reset preferences and re-choose backend
claudius --init --by-pass-start # Re-choose backend and model, write config, then exit (no start prompt)
claudius --purge # Clear session data interactively
claudius --last # Use last model and context; start Claude without menus
CLAUDIUS_BACKEND=ollama claudius # Use Ollama (if already configured)
CLAUDIUS_BACKEND=llamacpp claudius # llama-server (default URL/token from prefs or LLAMA_CPP_URL)
For more info: https://github.com/Somnius/Claudius-Bootstrapper
EOF
}
# Paths and defaults
CLAUDE_SETTINGS="${HOME}/.claude/settings.json"
CLAUDIUS_PREFS="${HOME}/.claude/claudius-prefs.json"
CLAUDE_HOME="${HOME}/.claude"
LMSTUDIO_URL="${LMSTUDIO_URL:-http://localhost:1234}"
OLLAMA_URL="${OLLAMA_URL:-http://localhost:11434}"
LLAMA_CPP_URL="${LLAMA_CPP_URL:-http://127.0.0.1:8080}"
# Claude Code appends /v1/messages — OpenRouter requires host .../api only (NOT .../api/v1). See openrouter.ai/docs Claude Code guide.
OPENROUTER_URL="${OPENROUTER_URL:-https://openrouter.ai/api}"
NVIDIA_URL="${NVIDIA_URL:-https://integrate.api.nvidia.com}"
LMSTUDIO_API="${LMSTUDIO_URL}/api/v1"
# NVIDIA NIM cloud documents OpenAI POST /v1/chat/completions; Claude Code uses Anthropic POST /v1/messages (see warn below).
warn_nvidia_claude_code_protocol() {
echo "" >&2
echo " --- NVIDIA API + Claude Code ---" >&2
echo " NVIDIA's public NIM API is OpenAI-style (POST /v1/chat/completions per docs.api.nvidia.com/nim/reference/llm-apis)." >&2
echo " Claude Code uses Anthropic Messages (POST /v1/messages). Model listing (GET /v1/models) works; chat usually does not." >&2
echo " Fix: use a proxy (LiteLLM, claude-code-proxy, etc.) as ANTHROPIC_BASE_URL, or a backend with native Anthropic APIs." >&2
echo "" >&2
}
# Session-related paths under ~/.claude to purge (do not include settings.json or claudius-prefs.json)
SESSION_DIRS="projects debug file-history tasks todos plans shell-snapshots session-env paste-cache"
# Curl timeout: connect + max total (avoid hanging)
CURL_TIMEOUT="${CURL_TIMEOUT:-10}"
# Cloud APIs (OpenRouter, custom): longer timeout + retries (Alibaba intl. can be slow or flaky on short timeouts)
CURL_TIMEOUT_CLOUD="${CURL_TIMEOUT_CLOUD:-25}"
# Alibaba Cloud DashScope (Singapore / intl.): OpenAI-compatible list vs Anthropic Messages for Claude Code — see README
DASHSCOPE_INTL_OPENAI_BASE="${DASHSCOPE_INTL_OPENAI_BASE:-https://dashscope-intl.aliyuncs.com/compatible-mode/v1}"
DASHSCOPE_INTL_ANTHROPIC_BASE="${DASHSCOPE_INTL_ANTHROPIC_BASE:-https://dashscope-intl.aliyuncs.com/apps/anthropic}"
# --- Platform detection: linux, darwin, or windows ---
detect_platform() {
local u
u=$(uname -s 2>/dev/null) || true
case "$u" in
Linux) echo "linux" ;;
Darwin) echo "darwin" ;;
MINGW*|MSYS*|CYGWIN*) echo "windows" ;;
*) echo "unknown" ;;
esac
}
# --- Shell detection for config file and export syntax ---
# Output: bash, zsh, fish, ksh, or sh. Prefer CLAUDIUS_SHELL, then SHELL, then infer.
get_current_shell() {
if [[ -n "${CLAUDIUS_SHELL:-}" ]]; then
case "${CLAUDIUS_SHELL}" in
bash|zsh|fish|ksh|sh) echo "${CLAUDIUS_SHELL}"; return ;;
esac
fi
if [[ -n "${SHELL:-}" ]]; then
case "$SHELL" in
*fish*) echo "fish"; return ;;
*zsh*) echo "zsh"; return ;;
*ksh*) echo "ksh"; return ;;
*bash*) echo "bash"; return ;;
esac
fi
[[ -n "${BASH:-}" ]] && echo "bash" && return
[[ -n "${ZSH_VERSION:-}" ]] && echo "zsh" && return
[[ -n "${FISH_VERSION:-}" ]] && echo "fish" && return
echo "bash"
}
# --- Config file path for the given shell ---
get_shell_config_file() {
local shell="${1:-bash}"
case "$shell" in
fish) echo "${HOME}/.config/fish/config.fish" ;;
zsh) echo "${HOME}/.zshrc" ;;
ksh) echo "${HOME}/.kshrc" ;;
sh) echo "${HOME}/.profile" ;;
*) echo "${HOME}/.bashrc" ;;
esac
}
# --- Absolute path to this script (for alias) ---
get_claudius_script_path() {
local dir
dir=$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" 2>/dev/null && pwd)
echo "${dir}/$(basename "${BASH_SOURCE[0]:-$0}")"
}
# --- Ensure ~/.local/bin is in shell config so 'claude' is in PATH in new terminals ---
ensure_path_for_claude_in_shell_config() {
local shell="${1:-bash}" config_file
config_file=$(get_shell_config_file "$shell")
[[ -d "${HOME}/.local/bin" ]] || return 0
if [[ -f "$config_file" ]] && grep -q '\.local/bin' "$config_file" 2>/dev/null; then
return 0
fi
local marker="# Claudius: ensure Claude Code CLI (claude) in PATH"
if [[ "$shell" == "fish" ]]; then
mkdir -p "${HOME}/.config/fish"
echo "" >> "$config_file"
echo "$marker" >> "$config_file"
echo 'set -gx PATH "$HOME/.local/bin" $PATH' >> "$config_file"
else
echo "" >> "$config_file"
echo "$marker" >> "$config_file"
echo 'export PATH="$HOME/.local/bin:$PATH"' >> "$config_file"
fi
echo " Appended ~/.local/bin to PATH in $config_file (for Claude Code CLI)."
}
# --- Ensure claudius alias is in shell config so 'claudius' works in new terminals ---
ensure_claudius_alias_in_shell_config() {
local shell="${1:-bash}" config_file script_path
config_file=$(get_shell_config_file "$shell")
script_path=$(get_claudius_script_path)
if [[ -f "$config_file" ]] && grep -qE 'alias claudius|function claudius' "$config_file" 2>/dev/null; then
return 0
fi
local marker="# Claudius bootstrapper alias (run: claudius)"
if [[ "$shell" == "fish" ]]; then
mkdir -p "${HOME}/.config/fish"
echo "" >> "$config_file"
echo "$marker" >> "$config_file"
echo "function claudius; $script_path \$argv; end" >> "$config_file"
else
echo "" >> "$config_file"
echo "$marker" >> "$config_file"
echo "alias claudius='$script_path'" >> "$config_file"
fi
echo " Appended claudius alias to $config_file."
}
# --- Append Claude Code env block to the correct config file with correct syntax ---
# Args: shell, base_url, auth_token, api_key, backend
# OpenRouter + NVIDIA API: ANTHROPIC_AUTH_TOKEN + empty ANTHROPIC_API_KEY (avoids Claude Code OAuth /login fallback). Alibaba DashScope /apps/anthropic (custom): same. Other custom|newapi: API_KEY only. lmstudio|ollama|llamacpp: AUTH_TOKEN.
update_shell_exports() {
local shell="${1:-bash}" base_url="$2" auth_token="${3:-}" api_key="${4:-}" backend="${5:-lmstudio}"
local config_file marker block
local dashscope_anthropic=0
[[ "$backend" == "custom" && "$base_url" == *"dashscope"* && "$base_url" == *"/apps/anthropic"* ]] && dashscope_anthropic=1
config_file=$(get_shell_config_file "$shell")
marker="# Claude Code → Claudius (ANTHROPIC_BASE_URL for backend)"
if [[ -f "$config_file" ]] && grep -q "ANTHROPIC_BASE_URL" "$config_file" 2>/dev/null && grep -q "$marker" "$config_file" 2>/dev/null; then
echo " Shell config already contains Claude Code env block: $config_file"
return 0
fi
if [[ "$shell" == "fish" ]]; then
mkdir -p "${HOME}/.config/fish"
case "$backend" in
openrouter|nvidia)
block="set -gx ANTHROPIC_BASE_URL \"${base_url}\"
set -gx ANTHROPIC_AUTH_TOKEN \"${api_key}\"
set -gx ANTHROPIC_API_KEY \"\"
set -gx CLAUDE_CODE_ATTRIBUTION_HEADER 0" ;;
custom)
if [[ $dashscope_anthropic -eq 1 ]]; then
block="set -gx ANTHROPIC_BASE_URL \"${base_url}\"
set -gx ANTHROPIC_AUTH_TOKEN \"${api_key}\"
set -gx ANTHROPIC_API_KEY \"\"
set -gx CLAUDE_CODE_ATTRIBUTION_HEADER 0"
else
block="set -gx ANTHROPIC_BASE_URL \"${base_url}\"
set -gx ANTHROPIC_API_KEY \"${api_key}\"
set -gx CLAUDE_CODE_ATTRIBUTION_HEADER 0"
fi ;;
newapi)
block="set -gx ANTHROPIC_BASE_URL \"${base_url}\"
set -gx ANTHROPIC_API_KEY \"${api_key}\"
set -gx CLAUDE_CODE_ATTRIBUTION_HEADER 0" ;;
llamacpp)
block="set -gx ANTHROPIC_BASE_URL \"${base_url}\"
set -gx ANTHROPIC_AUTH_TOKEN \"${auth_token}\"
set -gx ANTHROPIC_API_KEY \"\"
set -gx CLAUDE_CODE_ATTRIBUTION_HEADER 0
set -gx ENABLE_TOOL_SEARCH true
set -gx CLAUDE_CODE_AUTO_COMPACT_WINDOW 100000" ;;
*)
block="set -gx ANTHROPIC_BASE_URL \"${base_url}\"
set -gx ANTHROPIC_AUTH_TOKEN \"${auth_token}\"
set -gx CLAUDE_CODE_ATTRIBUTION_HEADER 0" ;;
esac
else
case "$backend" in
openrouter|nvidia)
block="export ANTHROPIC_BASE_URL=\"${base_url}\"
export ANTHROPIC_AUTH_TOKEN=\"${api_key}\"
export ANTHROPIC_API_KEY=\"\"
export CLAUDE_CODE_ATTRIBUTION_HEADER=0" ;;
custom)
if [[ $dashscope_anthropic -eq 1 ]]; then
block="export ANTHROPIC_BASE_URL=\"${base_url}\"
export ANTHROPIC_AUTH_TOKEN=\"${api_key}\"
export ANTHROPIC_API_KEY=\"\"
export CLAUDE_CODE_ATTRIBUTION_HEADER=0"
else
block="export ANTHROPIC_BASE_URL=\"${base_url}\"
export ANTHROPIC_API_KEY=\"${api_key}\"
export CLAUDE_CODE_ATTRIBUTION_HEADER=0"
fi ;;
newapi)
block="export ANTHROPIC_BASE_URL=\"${base_url}\"
export ANTHROPIC_API_KEY=\"${api_key}\"
export CLAUDE_CODE_ATTRIBUTION_HEADER=0" ;;
llamacpp)
block="export ANTHROPIC_BASE_URL=\"${base_url}\"
export ANTHROPIC_AUTH_TOKEN=\"${auth_token}\"
export ANTHROPIC_API_KEY=\"\"
export CLAUDE_CODE_ATTRIBUTION_HEADER=0
export ENABLE_TOOL_SEARCH=true
export CLAUDE_CODE_AUTO_COMPACT_WINDOW=100000" ;;
*)
block="export ANTHROPIC_BASE_URL=\"${base_url}\"
export ANTHROPIC_AUTH_TOKEN=\"${auth_token}\"
export CLAUDE_CODE_ATTRIBUTION_HEADER=0" ;;
esac
fi
echo "" >> "$config_file"
echo "$marker" >> "$config_file"
echo "$block" >> "$config_file"
echo " Appended Claude Code env block to: $config_file"
echo " Reload with: source $config_file (or open a new terminal)."
}
# --- First-time checks: LM Studio and required commands (run when prefs missing) ---
# Returns 0 if LM Studio appears installed (lms in PATH or common path), 1 otherwise.
check_lm_studio_installed() {
if command -v lms &>/dev/null; then
return 0
fi
[[ -x "${HOME}/.lmstudio/bin/lms" ]] && return 0
[[ -x "/opt/LM Studio/bin/lms" ]] 2>/dev/null && return 0
echo "LM Studio does not appear to be installed (no 'lms' command found)."
echo " Download and install from: https://lmstudio.ai/"
echo " Then run this script again with: claudius --init"
echo ""
return 1
}
# Returns 0 if Ollama appears installed (ollama in PATH), 1 otherwise.
check_ollama_installed() {
if command -v ollama &>/dev/null; then
return 0
fi
echo "Ollama does not appear to be installed (no 'ollama' command found)."
echo " Install from: https://ollama.com"
echo " Then run this script again with: claudius --init"
echo ""
return 1
}
# --- Try to install Claude Code CLI (Linux/macOS via official install script) ---
# Returns 0 if claude is in PATH after attempt, 1 otherwise. Adds ~/.local/bin to PATH for session.
try_install_claude_code() {
local plat
plat=$(detect_platform)
if [[ "$plat" == "windows" ]]; then
echo " On Windows, install Claude Code via WSL or see https://code.claude.com/docs"
return 1
fi
echo " Running official install script (https://claude.ai/install.sh)..."
if ! curl -fsSL https://claude.ai/install.sh 2>/dev/null | bash 2>/dev/null; then
echo " Install script failed or returned an error."
return 1
fi
export PATH="${HOME}/.local/bin:${PATH}"
if command -v claude &>/dev/null; then
echo " Claude Code installed. Run 'claude --version' to confirm."
ensure_path_for_claude_in_shell_config "$(get_current_shell)"
return 0
fi
echo " Install may have completed. Ensuring ~/.local/bin in your shell config..."
ensure_path_for_claude_in_shell_config "$(get_current_shell)"
echo " Reload your shell (source config file) or open a new terminal, then run claudius again."
return 1
}
# --- Ensure Claude Code CLI is installed; offer install if missing; persist PATH/alias in shell config ---
# Returns 0 if claude is available (now or after install), 1 otherwise.
ensure_claude_installed() {
[[ -d "${HOME}/.local/bin" ]] && export PATH="${HOME}/.local/bin:${PATH}"
if command -v claude &>/dev/null; then
return 0
fi
echo "Claude Code CLI (claude) is not installed or not in your PATH."
echo ""
local install_choice="y"
read -rp "Install Claude Code now? [Y/n]: " install_choice
install_choice="${install_choice:-y}"
if [[ "${install_choice,,}" != "n" && "${install_choice,,}" != "no" ]]; then
if try_install_claude_code; then
return 0
fi
fi
local cfg
cfg=$(get_shell_config_file "$(get_current_shell)")
ensure_path_for_claude_in_shell_config "$(get_current_shell)"
echo " Then run: source $cfg or open a new terminal, and run claudius again."
return 1
}
# Check required commands (curl; jq or python3; claude). Returns 0 if all ok, 1 otherwise. Prints install hints.
check_required_commands() {
local missing=()
# Prefer ~/.local/bin so we detect Claude Code if installed there but not yet in PATH (e.g. fresh install, IDE shell)
[[ -d "${HOME}/.local/bin" ]] && export PATH="${HOME}/.local/bin:${PATH}"
command -v curl &>/dev/null || missing+=("curl")
if ! command -v jq &>/dev/null && ! command -v python3 &>/dev/null; then
missing+=("jq or python3 (at least one for JSON)")
fi
command -v claude &>/dev/null || missing+=("claude (Claude Code CLI)")
if [[ ${#missing[@]} -eq 0 ]]; then
return 0
fi
# If only claude is missing, offer to install it
if [[ ${#missing[@]} -eq 1 && "${missing[0]}" == *"claude"* ]]; then
if ensure_claude_installed; then
return 0
fi
fi
echo "Missing required command(s): ${missing[*]}"
echo ""
echo "Install on your system, then run this script again with: claudius --init"
echo ""
local plat
plat=$(detect_platform)
case "$plat" in
linux)
if [[ -r /etc/os-release ]]; then
local id_like id
id=$(. /etc/os-release && echo "${ID:-}")
id_like=$(. /etc/os-release && echo "${ID_LIKE:-}")
if [[ "$id" == "debian" || "$id" == "ubuntu" || "$id" == "pika" || "$id_like" == *"debian"* ]]; then
echo " Debian/Ubuntu/PikaOS: sudo apt install curl jq"
elif [[ "$id" == "fedora" || "$id" == "rhel" || "$id_like" == *"fedora"* ]]; then
echo " Fedora/RHEL: sudo dnf install curl jq"
elif [[ "$id" == "arch" || "$id_like" == *"arch"* ]]; then
echo " Arch: sudo pacman -S curl jq"
else
echo " curl/jq: use your package manager (apt/dnf/pacman/zypper etc.)"
fi
else
echo " curl/jq: use your package manager"
fi
;;
darwin)
echo " macOS: brew install curl jq"
;;
windows)
echo " Windows: use WSL or Git Bash and install curl/jq there, or install from https://curl.se / https://jqlang.github.io/jq/"
;;
*)
echo " curl/jq: use your system package manager"
;;
esac
echo " python3: usually preinstalled; if not, install via your package manager"
echo " claude: see https://code.claude.com/docs for install instructions (Quickstart / your platform)"
echo ""
return 1
}
# --- Auth token for llamacpp: prefs authToken if key exists, else default lmstudio; explicit "" means no Bearer ---
get_llamacpp_auth_from_prefs() {
if [[ ! -f "$CLAUDIUS_PREFS" ]]; then
echo "lmstudio"
return
fi
if command -v jq &>/dev/null; then
if jq -e 'has("authToken")' "$CLAUDIUS_PREFS" &>/dev/null; then
jq -r '.authToken // ""' "$CLAUDIUS_PREFS"
return
fi
echo "lmstudio"
return
fi
python3 -c "
import json
try:
d = json.load(open('$CLAUDIUS_PREFS'))
print(d['authToken'] if 'authToken' in d else 'lmstudio')
except Exception:
print('lmstudio')
" 2>/dev/null || echo "lmstudio"
}
# --- Backend: read/save from prefs (backend, baseUrl, apiKey) ---
get_pref() {
local key="$1"
if [[ ! -f "$CLAUDIUS_PREFS" ]]; then
echo ""
return
fi
if command -v jq &>/dev/null; then
jq -r --arg k "$key" '.[$k] // ""' "$CLAUDIUS_PREFS" 2>/dev/null || echo ""
else
python3 -c "import json; f=open('$CLAUDIUS_PREFS'); d=json.load(f); print(d.get('$key', '') or '')" 2>/dev/null || echo ""
fi
}
# Merge new keys into existing prefs JSON (preserves showTurnDuration, keepSessionOnExit, etc.)
# Optional 4th arg: authToken (for llamacpp). If omitted, existing .authToken is left unchanged.
merge_prefs() {
local backend="$1" base_url="$2" api_key="${3:-}"
mkdir -p "$(dirname "$CLAUDIUS_PREFS")"
if [[ ! -f "$CLAUDIUS_PREFS" ]]; then
local at="${4:-}"
if command -v jq &>/dev/null; then
jq -n --arg b "$backend" --arg u "$base_url" --arg k "$api_key" --arg at "$at" \
'{backend: $b, baseUrl: $u, apiKey: $k, authToken: $at, showTurnDuration: true, keepSessionOnExit: true}' > "$CLAUDIUS_PREFS"
else
printf '%s\n' "{\"backend\": \"$backend\", \"baseUrl\": \"$base_url\", \"apiKey\": \"$api_key\", \"authToken\": \"$at\", \"showTurnDuration\": true, \"keepSessionOnExit\": true}" > "$CLAUDIUS_PREFS"
fi
return
fi
if command -v jq &>/dev/null; then
if [[ $# -ge 4 ]]; then
jq --arg b "$backend" --arg u "$base_url" --arg k "$api_key" --arg at "$4" \
'.backend = $b | .baseUrl = $u | .apiKey = $k | .authToken = $at' "$CLAUDIUS_PREFS" > "${CLAUDIUS_PREFS}.tmp" && mv "${CLAUDIUS_PREFS}.tmp" "$CLAUDIUS_PREFS"
else
jq --arg b "$backend" --arg u "$base_url" --arg k "$api_key" \
'.backend = $b | .baseUrl = $u | .apiKey = $k' "$CLAUDIUS_PREFS" > "${CLAUDIUS_PREFS}.tmp" && mv "${CLAUDIUS_PREFS}.tmp" "$CLAUDIUS_PREFS"
fi
else
if [[ $# -ge 4 ]]; then
CLAUDIUS_MERGE_AT="$4" python3 -c "
import json, os
at = os.environ.get('CLAUDIUS_MERGE_AT', '')
with open('$CLAUDIUS_PREFS') as f: d = json.load(f)
d['backend'] = '$backend'
d['baseUrl'] = '$base_url'
d['apiKey'] = '$api_key'
d['authToken'] = at
with open('$CLAUDIUS_PREFS','w') as f: json.dump(d, f, indent=2)
" 2>/dev/null || true
else
python3 -c "
import json
with open('$CLAUDIUS_PREFS') as f: d = json.load(f)
d['backend'] = '$backend'
d['baseUrl'] = '$base_url'
d['apiKey'] = '$api_key'
with open('$CLAUDIUS_PREFS','w') as f: json.dump(d, f, indent=2)
" 2>/dev/null || true
fi
fi
}
# --- Save last selected model and context length to prefs (for --last) ---
save_last_model_prefs() {
local model_id="$1" context_length="${2:-32768}"
[[ ! -f "$CLAUDIUS_PREFS" ]] && return 0
if command -v jq &>/dev/null; then
jq --arg m "$model_id" --argjson c "$context_length" '.lastModel = $m | .lastContextLength = $c' "$CLAUDIUS_PREFS" > "${CLAUDIUS_PREFS}.tmp" && mv "${CLAUDIUS_PREFS}.tmp" "$CLAUDIUS_PREFS"
else
python3 -c "
import json
with open('$CLAUDIUS_PREFS') as f: d = json.load(f)
d['lastModel'] = '$model_id'
d['lastContextLength'] = $context_length
with open('$CLAUDIUS_PREFS','w') as f: json.dump(d, f, indent=2)
" 2>/dev/null || true
fi
}
# --- First-time / --init: ask preferences and save to CLAUDIUS_PREFS ---
run_init() {
echo "Claudius first-time setup (preferences saved to $CLAUDIUS_PREFS)"
echo ""
local show_turn="y"
read -rp "Show reply duration after each response (e.g. 'Cooked for 1m 6s')? [Y/n]: " show_turn
show_turn="${show_turn:-y}"
local show_turn_bool=true
[[ "${show_turn,,}" == "n" || "${show_turn,,}" == "no" ]] && show_turn_bool=false
local keep_sess="y"
read -rp "Keep session history when Claude Code exits? [Y/n]: " keep_sess
keep_sess="${keep_sess:-y}"
local keep_sess_bool=true
[[ "${keep_sess,,}" == "n" || "${keep_sess,,}" == "no" ]] && keep_sess_bool=false
echo "Which backend should Claudius use?"
echo " 1) LM Studio (local, default http://localhost:1234)"
echo " 2) Ollama (local, default http://localhost:11434)"
echo " 3) OpenRouter (cloud; Claude Code base https://openrouter.ai/api — requires API key)"
echo " 4) Custom (Alibaba, Kimi, DeepSeek, Groq, OpenRouter, xAI, OpenAI, or other — API key)"
echo " 5) NewAPI (unified gateway — self‑host or cloud, https://github.com/QuantumNous/new-api)"
echo " 6) llama.cpp server (llama-server, OpenAI-compatible /v1; default http://127.0.0.1:8080)"
echo " 7) NVIDIA API (lists models only for most Claude Code use — host is OpenAI chat/completions, not Anthropic /messages; see note)"
echo ""
local backend_choice backend="lmstudio" base_url="$LMSTUDIO_URL" api_key="" auth_token_save=""
read -rp "Choose (1-7) [1]: " backend_choice
backend_choice="${backend_choice:-1}"
case "$backend_choice" in
1) backend="lmstudio"; base_url="${LMSTUDIO_URL}"; api_key="" ;;
2) backend="ollama"; base_url="${OLLAMA_URL}"; api_key="" ;;
3)
backend="openrouter"
base_url="${OPENROUTER_URL}"
read -rp "OpenRouter API key: " api_key
[[ -z "$api_key" ]] && echo " Warning: API key empty; list models may fail." >&2
;;
5)
backend="newapi"
read -rp "NewAPI base URL (e.g. http://localhost:8080 or https://your-newapi-host): " base_url
base_url="${base_url:-http://localhost:8080}"
read -rp "NewAPI API key (Bearer token): " api_key
[[ -z "$api_key" ]] && echo " Warning: API key empty; list models may fail." >&2
;;
4)
backend="custom"
echo "Choose custom provider (OpenAI-compatible API):"
echo " 1) Alibaba Cloud (DashScope) — Singapore: Anthropic API base for Claude Code (${DASHSCOPE_INTL_ANTHROPIC_BASE})"
echo " 2) Kimi (Moonshot AI) — global: api.moonshot.ai"
echo " 3) DeepSeek — api.deepseek.com"
echo " 4) Groq — api.groq.com/openai/v1"
echo " 5) OpenRouter — openrouter.ai (same as backend 3, alternative entry)"
echo " 6) xAI (Grok) — api.x.ai"
echo " 7) OpenAI — api.openai.com"
echo " 8) Other — enter base URL and API key"
echo ""
local custom_choice
read -rp "Choose (1-8) [1]: " custom_choice
custom_choice="${custom_choice:-1}"
case "$custom_choice" in
1) base_url="${DASHSCOPE_INTL_ANTHROPIC_BASE}" ;;
2) base_url="https://api.moonshot.ai/v1" ;;
3) base_url="https://api.deepseek.com/v1" ;;
4) base_url="https://api.groq.com/openai/v1" ;;
5) base_url="${OPENROUTER_URL}" ;;
6) base_url="https://api.x.ai/v1" ;;
7) base_url="https://api.openai.com/v1" ;;
8)
read -rp "Custom API base URL (e.g. https://api.example.com/v1): " base_url
;;
*) base_url="${DASHSCOPE_INTL_ANTHROPIC_BASE}" ;;
esac
read -rp "API key: " api_key
[[ -z "$api_key" ]] && echo " Warning: API key empty; list models may fail." >&2
[[ "$custom_choice" == "8" && -z "$base_url" ]] && echo " Warning: Base URL empty; list models may fail." >&2
;;
6)
backend="llamacpp"
read -rp "llama.cpp server base URL [http://127.0.0.1:8080]: " base_url
base_url="${base_url:-http://127.0.0.1:8080}"
if ! base_url=$(normalize_remote_url "$base_url" 8080); then
base_url="http://127.0.0.1:8080"
fi
local llama_tok
read -rp "Bearer/API token → ANTHROPIC_AUTH_TOKEN [lmstudio]: " llama_tok
llama_tok="${llama_tok:-lmstudio}"
auth_token_save="$llama_tok"
api_key=""
;;
7)
backend="nvidia"
read -rp "NVIDIA API host [${NVIDIA_URL}]: " nv_host
nv_host="${nv_host:-$NVIDIA_URL}"
nv_host="${nv_host%/}"
[[ "$nv_host" == */v1 ]] && nv_host="${nv_host%/v1}"
base_url="$nv_host"
read -rp "NVIDIA API key (Bearer, from build.nvidia.com): " api_key
[[ -z "$api_key" ]] && echo " Warning: API key empty; list models may fail." >&2
warn_nvidia_claude_code_protocol
;;
*) backend="lmstudio"; base_url="${LMSTUDIO_URL}"; api_key="" ;;
esac
mkdir -p "$(dirname "$CLAUDIUS_PREFS")"
if command -v jq &>/dev/null; then
jq -n \
--arg st "$show_turn_bool" --arg ks "$keep_sess_bool" \
--arg b "$backend" --arg u "$base_url" --arg k "$api_key" --arg at "$auth_token_save" \
'{showTurnDuration: ($st == "true"), keepSessionOnExit: ($ks == "true"), backend: $b, baseUrl: $u, apiKey: $k, authToken: $at}' > "$CLAUDIUS_PREFS"
else
CLAUDIUS_INIT_AT="$auth_token_save" python3 -c "
import json, os
d = {
'showTurnDuration': $show_turn_bool,
'keepSessionOnExit': $keep_sess_bool,
'backend': '$backend',
'baseUrl': '$base_url',
'apiKey': '$api_key',
'authToken': os.environ.get('CLAUDIUS_INIT_AT', ''),
}
with open('$CLAUDIUS_PREFS', 'w') as f:
json.dump(d, f, indent=2)
" 2>/dev/null || printf '%s\n' "{\"showTurnDuration\": $show_turn_bool, \"keepSessionOnExit\": $keep_sess_bool, \"backend\": \"$backend\", \"baseUrl\": \"$base_url\", \"apiKey\": \"$api_key\", \"authToken\": \"\"}" > "$CLAUDIUS_PREFS"
fi
echo " Saved. Run claudius --init again anytime to change these."
echo ""
}
# --- Read showTurnDuration from prefs; default true. Must output lowercase "true" or "false" for write_settings. ---
get_show_turn_duration() {
if [[ ! -f "$CLAUDIUS_PREFS" ]]; then
echo "true"
return
fi
if command -v jq &>/dev/null; then
jq -r '(.showTurnDuration // true) | if . then "true" else "false" end' "$CLAUDIUS_PREFS" 2>/dev/null || echo "true"
else
python3 -c "import json; v=json.load(open('$CLAUDIUS_PREFS')).get('showTurnDuration', True); print('true' if v else 'false')" 2>/dev/null || echo "true"
fi
}
# --- Read keepSessionOnExit from prefs; default true. Output lowercase "true" or "false" for main. ---
get_keep_session_on_exit() {
if [[ ! -f "$CLAUDIUS_PREFS" ]]; then
echo "true"
return
fi
if command -v jq &>/dev/null; then
jq -r '(.keepSessionOnExit // true) | if . then "true" else "false" end' "$CLAUDIUS_PREFS" 2>/dev/null || echo "true"
else
python3 -c "import json; v=json.load(open('$CLAUDIUS_PREFS')).get('keepSessionOnExit', True); print('true' if v else 'false')" 2>/dev/null || echo "true"
fi
}
# --- PURGE SAFETY: Session data is destructive. ---
# These functions must ONLY be called from run_purge() or run_after_session_menu(),
# and ONLY for the specific option the user chose. Never call a purge automatically
# or from any path that does not require explicit user input for that choice.
# --- Purge session data: delete files in SESSION_DIRS and optionally history.jsonl ---
# Usage: purge_session_dirs [optional: also_clear_history 1]
# If also_clear_history=1, truncate/remove history.jsonl.
purge_session_dirs() {
local also_history="${1:-0}"
local d
for d in $SESSION_DIRS; do
[[ -d "${CLAUDE_HOME}/${d}" ]] && rm -rf "${CLAUDE_HOME}/${d}"/*
done
if [[ "$also_history" == "1" ]] && [[ -f "${CLAUDE_HOME}/history.jsonl" ]]; then
: > "${CLAUDE_HOME}/history.jsonl"
fi
}
# --- Purge session files older than N minutes (mtime < now - N min) ---
purge_older_than_mins() {
local mins="$1"
[[ -z "$mins" || ! "$mins" =~ ^[0-9]+$ ]] && return 1
local d
for d in $SESSION_DIRS; do
[[ -d "${CLAUDE_HOME}/${d}" ]] || continue
find "${CLAUDE_HOME}/${d}" -type f -mmin "+${mins}" -delete 2>/dev/null || true
find "${CLAUDE_HOME}/${d}" -type d -empty -delete 2>/dev/null || true
done
# history.jsonl: remove lines with timestamp older than N min (timestamp is ms)
if [[ -f "${CLAUDE_HOME}/history.jsonl" ]]; then
local cutoff_ms
cutoff_ms=$(($(date +%s) * 1000 - mins * 60 * 1000))
if command -v jq &>/dev/null; then
jq -c --argjson c "$cutoff_ms" 'select(.timestamp >= $c)' "${CLAUDE_HOME}/history.jsonl" 2>/dev/null > "${CLAUDE_HOME}/history.jsonl.tmp" && mv "${CLAUDE_HOME}/history.jsonl.tmp" "${CLAUDE_HOME}/history.jsonl"
else
python3 -c "
import sys, json
cutoff = $cutoff_ms
with open('${CLAUDE_HOME}/history.jsonl') as f:
lines = [l for l in f if l.strip() and json.loads(l).get('timestamp', 0) >= cutoff]
with open('${CLAUDE_HOME}/history.jsonl', 'w') as f:
f.writelines(lines)
" 2>/dev/null || true
fi
fi
}
# --- Purge session files from yesterday and back (mtime before today 00:00) ---
purge_yesterday_and_back() {
local now_sec today_start_sec mins
now_sec=$(date +%s)
today_start_sec=$(python3 -c "from datetime import datetime; d=datetime.now().replace(hour=0,minute=0,second=0,microsecond=0); print(int(d.timestamp()))" 2>/dev/null) || today_start_sec=0
mins=$(( (now_sec - today_start_sec) / 60 ))
[[ "$mins" -lt 1 ]] && mins=1
purge_older_than_mins "$mins"
}
# --- Purge recent session (last 2 min) - used after exit when keepSessionOnExit=false ---
purge_session_recent() {
# Delete files modified in the last 2 minutes (current session)
local d
for d in $SESSION_DIRS; do
[[ -d "${CLAUDE_HOME}/${d}" ]] || continue
find "${CLAUDE_HOME}/${d}" -type f -mmin -2 -delete 2>/dev/null || true
find "${CLAUDE_HOME}/${d}" -type d -empty -delete 2>/dev/null || true
done
}
# --- --purge: interactive menu, then run chosen purge ---
run_purge() {
echo "Claudius — purge saved session data under $CLAUDE_HOME"
echo ""
echo " 1) Purge ALL session data (2 verification questions)"
echo " 2) Purge last session only (last ~2 min)"
echo " 3) Purge all from yesterday and back"
echo " 4) Purge all from 6 hours and back"
echo " 5) Purge all from 3 hours and back"
echo " 6) Purge all from 2 hours and back"
echo " 7) Purge all from 1 hour and back"
echo " 8) Purge all from 30 minutes and back"
echo " q) Cancel"
echo ""
local choice
read -rp "Choose (1-8 or q): " choice
case "$choice" in
q|Q) echo "Cancelled."; return 0 ;;
1)
read -rp "Type YES to confirm purge of ALL session data: " a
[[ "${a^^}" != "YES" ]] && echo "Cancelled." && return 0
read -rp "Type PURGE to confirm again: " b
[[ "${b^^}" != "PURGE" ]] && echo "Cancelled." && return 0
purge_session_dirs 1
echo " Purged all session data."
;;
2) purge_session_recent; echo " Purged last session only." ;;
3) purge_yesterday_and_back; echo " Purged session data from yesterday and back." ;;
4) purge_older_than_mins 360; echo " Purged session data older than 6 hours." ;;
5) purge_older_than_mins 180; echo " Purged session data older than 3 hours." ;;
6) purge_older_than_mins 120; echo " Purged session data older than 2 hours." ;;
7) purge_older_than_mins 60; echo " Purged session data older than 1 hour." ;;
8) purge_older_than_mins 30; echo " Purged session data older than 30 minutes." ;;
*) echo "Invalid choice. No data purged."; return 0 ;;
esac
return 0
}
# --- After session (when keepSessionOnExit=false): menu to delete current session or purge by age ---
run_after_session_menu() {
echo "Session ended. Delete session data?"
echo ""
echo " 1) Delete current session only (last ~2 min)"
echo " 2) Purge ALL session data (2 verification questions)"
echo " 3) Purge all from yesterday and back"
echo " 4) Purge all from 6 hours and back"
echo " 5) Purge all from 3 hours and back"
echo " 6) Purge all from 2 hours and back"
echo " 7) Purge all from 1 hour and back"
echo " 8) Purge all from 30 minutes and back"
echo " 9) Skip (keep everything)"
echo ""
local choice
read -rp "Choose (1-9): " choice
# Only the exact option chosen by the user triggers a purge; anything else skips.
case "$choice" in
1) purge_session_recent; echo " Deleted current session." ;;
2)
read -rp "Type YES to confirm purge of ALL session data: " a
[[ "${a^^}" != "YES" ]] && echo "Skipped. No data purged." && return 0
read -rp "Type PURGE to confirm again: " b
[[ "${b^^}" != "PURGE" ]] && echo "Skipped. No data purged." && return 0
purge_session_dirs 1
echo " Purged all session data."
;;
3) purge_yesterday_and_back; echo " Purged session data from yesterday and back." ;;
4) purge_older_than_mins 360; echo " Purged session data older than 6 hours." ;;
5) purge_older_than_mins 180; echo " Purged session data older than 3 hours." ;;
6) purge_older_than_mins 120; echo " Purged session data older than 2 hours." ;;
7) purge_older_than_mins 60; echo " Purged session data older than 1 hour." ;;
8) purge_older_than_mins 30; echo " Purged session data older than 30 minutes." ;;
9|q|Q) echo " Skipped. No data purged." ;;
*) echo " Skipped. No data purged." ;;
esac
return 0
}
# --- Normalize user-entered server address to base URL (http://host:port) ---
# Args: address (e.g. 192.168.1.10:1234, myserver, http://host:11434), default_port
# Output: base URL (no trailing slash)
normalize_remote_url() {
local raw="${1:-}" default_port="${2:-1234}"
raw=$(echo "$raw" | tr -d ' \t')
[[ -z "$raw" ]] && echo "" && return 1
if [[ "$raw" == https://* || "$raw" == http://* ]]; then
echo "${raw%/}"
return 0
fi
if [[ "$raw" =~ ^([^:]+):([0-9]+)$ ]]; then
echo "http://${BASH_REMATCH[1]}:${BASH_REMATCH[2]}"
return 0
fi
echo "http://${raw}:${default_port}"
return 0
}
# --- Prompt for remote server address and backend type; set CURRENT_BASE_URL, CURRENT_BACKEND and save to prefs ---
# Optional $1: fixed_backend = lmstudio|ollama|llamacpp — skip "which backend" menu (same backend as current flow).
# When fixed_backend is set, Enter alone keeps CURRENT_BASE_URL (retry / confirm without retyping).
prompt_remote_server() {
local fixed_backend="${1:-}"
local addr backend_num default_port default_hint=""
echo "Connect to a remote server (e.g. another machine on your network)."
if [[ -n "${CURRENT_BASE_URL:-}" ]]; then
default_hint="${CURRENT_BASE_URL#http://}"
default_hint="${default_hint#https://}"
fi
if [[ -n "$default_hint" ]]; then
if [[ -n "$fixed_backend" ]]; then
read -rp "Enter server address (host or IP:port) [${default_hint}, Enter=keep]: " addr
else
read -rp "Enter server address (host or IP:port) [${default_hint}]: " addr
fi
else
read -rp "Enter server address (host or IP:port, e.g. 192.168.1.10:1234): " addr
fi
addr=$(echo "$addr" | tr -d ' \t')
if [[ -z "$addr" ]]; then
if [[ -n "$fixed_backend" && -n "${CURRENT_BASE_URL:-}" ]]; then
addr="$CURRENT_BASE_URL"
else
echo " No address entered. Skipped."
return 1
fi
fi
if [[ -n "$fixed_backend" ]]; then
CURRENT_BACKEND="$fixed_backend"
case "$fixed_backend" in
lmstudio) default_port=1234 ;;
ollama) default_port=11434 ;;
llamacpp) default_port=8080 ;;
*) echo " Internal error: bad fixed_backend."; return 1 ;;
esac
else
echo ""
echo "Backend running on this server:"
echo " 1) LM Studio (default port 1234)"
echo " 2) Ollama (default port 11434)"
echo " 3) llama.cpp server / llama-server (default port 8080)"
read -rp "Choose (1-3) [1]: " backend_num
backend_num="${backend_num:-1}"
case "$backend_num" in
1) CURRENT_BACKEND="lmstudio"; default_port=1234 ;;
2) CURRENT_BACKEND="ollama"; default_port=11434 ;;
3) CURRENT_BACKEND="llamacpp"; default_port=8080 ;;
*) echo " Invalid choice. Using LM Studio (1234)."; CURRENT_BACKEND="lmstudio"; default_port=1234 ;;
esac
fi
CURRENT_BASE_URL=$(normalize_remote_url "$addr" "$default_port")
if [[ -z "$CURRENT_BASE_URL" ]]; then
echo " Could not parse address. Skipped."
return 1
fi
case "$CURRENT_BACKEND" in
lmstudio) CURRENT_AUTH="lmstudio" ;;
ollama) CURRENT_AUTH="" ;;
llamacpp)
CURRENT_AUTH=$(get_llamacpp_auth_from_prefs)
;;
*) CURRENT_AUTH="$CURRENT_API_KEY" ;;
esac
merge_prefs "$CURRENT_BACKEND" "$CURRENT_BASE_URL" "$CURRENT_API_KEY"
echo " Using $CURRENT_BACKEND @ $CURRENT_BASE_URL"
return 0
}
# --- Resolve backend from env or prefs; set CURRENT_BACKEND, CURRENT_BASE_URL, CURRENT_API_KEY, CURRENT_AUTH ---
resolve_backend() {
if [[ -n "${CLAUDIUS_BACKEND:-}" ]]; then
CURRENT_BACKEND="$CLAUDIUS_BACKEND"
CURRENT_BASE_URL="${CLAUDIUS_BASE_URL:-}"
CURRENT_API_KEY="${CLAUDIUS_API_KEY:-}"
else
CURRENT_BACKEND=$(get_pref "backend")
CURRENT_BASE_URL=$(get_pref "baseUrl")
CURRENT_API_KEY=$(get_pref "apiKey")
fi
# Defaults when empty
[[ -z "$CURRENT_BACKEND" ]] && CURRENT_BACKEND="lmstudio"
if [[ -z "$CURRENT_BASE_URL" ]]; then
case "$CURRENT_BACKEND" in
lmstudio) CURRENT_BASE_URL="${LMSTUDIO_URL}" ;;
ollama) CURRENT_BASE_URL="${OLLAMA_URL}" ;;
llamacpp) CURRENT_BASE_URL="${LLAMA_CPP_URL}" ;;
openrouter) CURRENT_BASE_URL="${OPENROUTER_URL}" ;;
nvidia) CURRENT_BASE_URL="${NVIDIA_URL}" ;;
newapi) ;; # no default; user must set in prefs
*) CURRENT_BASE_URL="" ;;
esac
fi
# llama.cpp: prefs may store host:port without scheme — curl needs http://...
if [[ "$CURRENT_BACKEND" == "llamacpp" && -n "$CURRENT_BASE_URL" && "$CURRENT_BASE_URL" != http://* && "$CURRENT_BASE_URL" != https://* ]]; then
local _llama_nu
_llama_nu=$(normalize_remote_url "$CURRENT_BASE_URL" 8080) || true
[[ -n "$_llama_nu" ]] && CURRENT_BASE_URL="$_llama_nu"
fi
[[ -z "$CURRENT_API_KEY" ]] && CURRENT_API_KEY=""
# Auth token for Claude Code settings: LM Studio uses placeholder; llamacpp uses prefs or env; cloud uses API key
case "$CURRENT_BACKEND" in
lmstudio) CURRENT_AUTH="lmstudio" ;;
ollama) CURRENT_AUTH="" ;;
llamacpp)
CURRENT_AUTH="${CLAUDIUS_AUTH_TOKEN:-}"
[[ -z "$CURRENT_AUTH" ]] && CURRENT_AUTH=$(get_llamacpp_auth_from_prefs)
;;
*) CURRENT_AUTH="$CURRENT_API_KEY" ;;
esac
# Alibaba DashScope (intl.): Claude Code uses Anthropic Messages → ANTHROPIC_BASE_URL must be .../apps/anthropic (not .../compatible-mode/v1).
# Model listing uses OpenAI-compatible .../compatible-mode/v1. See https://www.alibabacloud.com/help/en/model-studio/anthropic-api-messages
unset -v CURRENT_CUSTOM_LIST_URL 2>/dev/null || true
if [[ "$CURRENT_BACKEND" == "custom" ]]; then
if [[ "$CURRENT_BASE_URL" == *"dashscope-intl.aliyuncs.com"* ]]; then
if [[ "$CURRENT_BASE_URL" == *"/compatible-mode"* ]]; then
local dashscope_migrate_prefs=0
CURRENT_CUSTOM_LIST_URL="$CURRENT_BASE_URL"
if [[ -z "${CLAUDIUS_BACKEND:-}" && -z "${CLAUDIUS_BASE_URL:-}" && -f "$CLAUDIUS_PREFS" ]]; then
local saved_base
saved_base=$(get_pref "baseUrl")
[[ "$saved_base" == *"/compatible-mode"* ]] && dashscope_migrate_prefs=1
fi
CURRENT_BASE_URL="$DASHSCOPE_INTL_ANTHROPIC_BASE"
if [[ "$dashscope_migrate_prefs" -eq 1 ]]; then
merge_prefs "custom" "$CURRENT_BASE_URL" "$CURRENT_API_KEY" || true
echo " Updated prefs: Alibaba base URL → ${DASHSCOPE_INTL_ANTHROPIC_BASE} (Anthropic API for Claude Code). Model list: ${CURRENT_CUSTOM_LIST_URL}." >&2
fi
elif [[ "$CURRENT_BASE_URL" == *"/apps/anthropic"* ]]; then
CURRENT_CUSTOM_LIST_URL="$DASHSCOPE_INTL_OPENAI_BASE"
else
CURRENT_CUSTOM_LIST_URL="$CURRENT_BASE_URL"
fi
else
CURRENT_CUSTOM_LIST_URL="$CURRENT_BASE_URL"
fi
fi
# OpenRouter: ANTHROPIC_BASE_URL must be https://openrouter.ai/api (Claude Code adds /v1/messages). Old .../api/v1 breaks chat.
if [[ "$CURRENT_BACKEND" == "openrouter" ]]; then
if [[ "$CURRENT_BASE_URL" == *"openrouter.ai/api/v1"* ]]; then
local or_migrate_prefs=0
if [[ -z "${CLAUDIUS_BACKEND:-}" && -z "${CLAUDIUS_BASE_URL:-}" && -f "$CLAUDIUS_PREFS" ]]; then
local saved_or
saved_or=$(get_pref "baseUrl")
[[ "$saved_or" == *"openrouter.ai/api/v1"* ]] && or_migrate_prefs=1
fi
CURRENT_BASE_URL="https://openrouter.ai/api"
if [[ "$or_migrate_prefs" -eq 1 ]]; then
merge_prefs "openrouter" "$CURRENT_BASE_URL" "$CURRENT_API_KEY" || true
echo " Updated prefs: OpenRouter base URL → https://openrouter.ai/api (required for Claude Code; see OpenRouter docs)." >&2