Repository navigation
Expand file tree
/
Copy pathods-cli
More file actions
executable file
·7378 lines (6671 loc) · 303 KB
/
Copy pathods-cli
File metadata and controls
executable file
·7378 lines (6671 loc) · 303 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
# ods-cli - Command line interface for ODS
# Mission: M5 (Clonable ODS Setup Server)
# Registry-driven service resolution; VERSION below is the product version.
set -euo pipefail
# Require Bash 4+ (associative arrays used by service registry and ods-cli)
if (( BASH_VERSINFO[0] < 4 )); then
# macOS starts env bash with Apple's Bash 3.2 even after Homebrew installs
# Bash 4+. Re-exec the installed modern Bash before using associative arrays.
for _ods_modern_bash in /opt/homebrew/bin/bash /usr/local/bin/bash; do
if [[ -x "$_ods_modern_bash" ]] &&
"$_ods_modern_bash" -c '(( BASH_VERSINFO[0] >= 4 ))' >/dev/null 2>&1; then
exec "$_ods_modern_bash" "$0" "$@"
fi
done
echo -e "\033[0;31m✗\033[0m ods-cli requires Bash 4.0+ (you have $BASH_VERSION)" >&2
echo " macOS ships Bash 3.2 due to licensing. Install a modern version:" >&2
echo " brew install bash" >&2
echo " Then re-run with: /opt/homebrew/bin/bash $0 $*" >&2
exit 1
fi
#=============================================================================
# Configuration
#=============================================================================
_source="${BASH_SOURCE[0]}"
while [[ -L "$_source" ]]; do
_dir="$(cd "$(dirname "$_source")" && pwd)"
_source="$(readlink "$_source")"
[[ "$_source" != /* ]] && _source="$_dir/$_source"
done
SCRIPT_DIR="$(cd "$(dirname "$_source")" && pwd)"
_resolve_cli_install_dir() {
if [[ -n "${INSTALL_DIR:-}" ]]; then
printf '%s\n' "$INSTALL_DIR"
elif [[ -n "${ODS_HOME:-}" ]]; then
printf '%s\n' "$ODS_HOME"
elif [[ -n "${ODS_SCRIPT_HINT:-}" ]] && [[ -f "$ODS_SCRIPT_HINT/.env" ]]; then
printf '%s\n' "$ODS_SCRIPT_HINT"
elif [[ -n "${ODS_INSTALL_DIR:-}" ]]; then
printf '%s\n' "$ODS_INSTALL_DIR"
elif [[ -f "$SCRIPT_DIR/docker-compose.base.yml" || -f "$SCRIPT_DIR/docker-compose.yml" ]]; then
# Installed copies and symlink targets are self-locating. This keeps a
# custom-path CLI from silently operating on an unrelated $HOME/ods.
printf '%s\n' "$SCRIPT_DIR"
else
printf '%s\n' "$HOME/ods"
fi
}
INSTALL_DIR="$(_resolve_cli_install_dir)"
VERSION="3.0.0"
if [[ -f "$INSTALL_DIR/.env" ]]; then
_v=$(awk -F= '/^ODS_VERSION=/{gsub(/^["'"'"']|["'"'"']$/,"",$2); print $2; exit}' "$INSTALL_DIR/.env" 2>/dev/null) || true
[[ -n "${_v:-}" ]] && VERSION="$_v"
fi
# Colors — use ANSI-C quoting ($'\033') so the variables hold real ESC bytes
# at assignment time. Single-quoted strings store the backslash literally,
# which breaks unquoted heredocs (cmd_help) that never re-interpret escapes.
# Guard on TTY + NO_COLOR so redirected / piped output stays clean.
# Per no-color.org, NO_COLOR disables colors when it is present (set to any
# value, including empty), so we check set-ness with ${NO_COLOR+x} — which
# expands to "x" whenever NO_COLOR is set and to "" only when truly unset —
# rather than ${NO_COLOR:-} which would treat NO_COLOR="" as unset.
if [[ -t 1 ]] && [[ -z "${NO_COLOR+x}" ]]; then
RED=$'\033[0;31m'
GREEN=$'\033[0;32m'
YELLOW=$'\033[1;33m'
BLUE=$'\033[0;34m'
CYAN=$'\033[0;36m'
NC=$'\033[0m'
else
RED=''
GREEN=''
YELLOW=''
BLUE=''
CYAN=''
NC=''
fi
#=============================================================================
# Helpers
#=============================================================================
log() { echo -e "${CYAN}[ods]${NC} $1" >&2; }
success() { echo -e "${GREEN}✓${NC} $1"; }
warn() { echo -e "${YELLOW}⚠${NC} $1" >&2; }
error() { echo -e "${RED}✗${NC} $1" >&2; exit 1; }
log_error() { echo -e "${RED}✗${NC} $1" >&2; }
# A failed remote-provider operation also says where to get help.
_remote_provider_fail() {
echo -e "${RED}✗${NC} $1" >&2
echo " Need help? Ask on the ODS Discord: https://discord.gg/4ntNp9MAwC" >&2
exit 1
}
# Map cmd_list status string to a colour. Returns an empty string for unknown
# statuses so future state names don't break formatting.
_status_color() {
case "$1" in
enabled|always-on) echo "$GREEN" ;;
disabled|stopped) echo "$YELLOW" ;;
unhealthy|error) echo "$RED" ;;
*) echo "" ;;
esac
}
_json_escape() {
local s="${1-}"
s=${s//\\/\\\\}
s=${s//\"/\\\"}
s=${s//$'\b'/\\b}
s=${s//$'\f'/\\f}
s=${s//$'\n'/\\n}
s=${s//$'\r'/\\r}
s=${s//$'\t'/\\t}
printf '%s' "$s"
}
# Print a separator of repeated characters filling the given width.
# Usage: hr <width> [<char=─>]
hr() {
local w="${1:-10}" c="${2:-─}" out=''
printf -v out '%*s' "$w" ''
printf '%s' "${out// /$c}"
}
# Update or add a key=value in .env
_env_set() {
local key="$1" val="$2" file="$INSTALL_DIR/.env"
# The probe must use the same literal-prefix test as the awk update below:
# a regex here treats dots/brackets in the key as wildcards, so a key like
# FOO.BAR could "match" FOO_BAR=... and then be silently dropped by awk.
if awk -v k="$key" 'index($0, k "=") == 1 { found = 1 } END { exit !found }' "$file" 2>/dev/null; then
# Use awk to avoid sed delimiter collisions with values containing | / or =
awk -v k="$key" -v v="$val" '{
if (index($0, k "=") == 1) print k "=" v; else print
}' "$file" > "${file}.tmp" && cat "${file}.tmp" > "$file" && rm -f "${file}.tmp"
else
# Appending after a last line that has no newline would join the new
# assignment onto that line and corrupt both keys.
if [[ -s "$file" && -n "$(tail -c 1 "$file")" ]]; then
printf '\n' >> "$file"
fi
echo "${key}=${val}" >> "$file"
fi
}
_env_unset() {
local key="$1" file="$INSTALL_DIR/.env"
[[ -f "$file" ]] || return 0
awk -v k="$key" 'index($0, k "=") != 1 { print }' "$file" > "${file}.tmp" \
&& cat "${file}.tmp" > "$file" \
&& rm -f "${file}.tmp"
}
_env_get_raw() {
local key="$1" file="$INSTALL_DIR/.env"
[[ -f "$file" ]] || { echo ""; return 0; }
awk -v k="$key" '
index($0, k "=") == 1 { value = substr($0, length(k) + 2); found = 1 }
END { if (found) print value }
' "$file" 2>/dev/null | tr -d '\r' || true
}
_ensure_hermes_dashboard_session_token() {
[[ -f "$INSTALL_DIR/.env" ]] || return 0
[[ -n "$(_env_get_raw HERMES_DASHBOARD_SESSION_TOKEN)" ]] && return 0
local token
if command -v openssl >/dev/null 2>&1; then
token="$(openssl rand -hex 32)"
else
token="$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')"
fi
[[ "$token" =~ ^[0-9a-f]{64}$ ]] \
|| error "Could not generate HERMES_DASHBOARD_SESSION_TOKEN"
_env_set "HERMES_DASHBOARD_SESSION_TOKEN" "$token"
}
_ods_cli_proxy_enabled() {
[[ -f "$INSTALL_DIR/extensions/services/ods-proxy/compose.yaml" ]] \
|| [[ -f "$INSTALL_DIR/data/user-extensions/ods-proxy/compose.yaml" ]]
}
# A BIND_ADDRESS other than loopback publishes Open WebUI beyond this machine,
# with or without the ODS proxy, so it needs the same sign-in enforcement.
_ods_cli_bind_is_network() {
local bind
bind="$(_env_get_raw BIND_ADDRESS)"
bind="${bind#\"}"; bind="${bind%\"}"; bind="${bind#\'}"; bind="${bind%\'}"
case "${bind:-127.0.0.1}" in
127.0.0.1|::1|\[::1\]|localhost) return 1 ;;
*) return 0 ;;
esac
}
_ods_cli_network_access_enabled() {
_ods_cli_proxy_enabled || _ods_cli_bind_is_network
}
_ods_cli_require_proxy_auth() {
[[ -f "$INSTALL_DIR/.env" ]] \
|| error "Cannot enable network access without $INSTALL_DIR/.env."
if [[ "$(_env_get_raw WEBUI_AUTH)" != "true" ]]; then
_env_set "WEBUI_AUTH" "true" \
|| error "Could not enforce WEBUI_AUTH=true before enabling network access."
log " Network access requires sign-in; set WEBUI_AUTH=true."
fi
export WEBUI_AUTH=true
}
_ods_cli_prepare_proxy_start() {
local -a compose_flags=("$@")
_ods_cli_require_proxy_auth
_compose_run_with_summary \
"Applying authenticated Open WebUI configuration" \
"${compose_flags[@]}" up -d --no-deps --force-recreate open-webui
}
_ods_cli_bootstrap_status() {
local status_file="$INSTALL_DIR/data/bootstrap-status.json"
[[ -f "$status_file" ]] || return 0
grep -o '"status"[[:space:]]*:[[:space:]]*"[^"]*"' "$status_file" \
| sed -n '1p' \
| sed 's/.*"status"[[:space:]]*:[[:space:]]*"//' \
| sed 's/"//' \
|| true
}
_ods_cli_bootstrap_status_field() {
local key="$1" status_file="$INSTALL_DIR/data/bootstrap-status.json"
[[ -f "$status_file" ]] || return 0
grep -o "\"${key}\"[[:space:]]*:[[:space:]]*\"[^\"]*\"" "$status_file" \
| sed -n '1p' \
| sed "s/.*\"${key}\"[[:space:]]*:[[:space:]]*\"//" \
| sed 's/"//' \
|| true
}
_ods_cli_bootstrap_status_number() {
local key="$1" status_file="$INSTALL_DIR/data/bootstrap-status.json"
[[ -f "$status_file" ]] || return 0
grep -o "\"${key}\"[[:space:]]*:[[:space:]]*[0-9][0-9.]*" "$status_file" \
| sed -n '1p' \
| sed "s/.*:[[:space:]]*//" \
|| true
}
_ods_cli_file_size() {
local path="$1"
if stat -c %s "$path" 2>/dev/null; then
return 0
fi
stat -f %z "$path" 2>/dev/null || echo 0
}
_ods_cli_bootstrap_upgrade_process_running() {
local model="$1" args
[[ -n "$model" ]] || return 1
while IFS= read -r args; do
case "$args" in
*"/scripts/bootstrap-upgrade.sh"*" $model "*|*" scripts/bootstrap-upgrade.sh"*" $model "*)
return 0
;;
esac
done < <(ps -eo args= 2>/dev/null || true)
return 1
}
_ods_cli_bootstrap_active_status_settled() {
local status="$1"
case "$status" in
downloading|starting|verifying|swapping) ;;
*) return 1 ;;
esac
local model env_model model_path expected_bytes actual_bytes
model="$(_ods_cli_bootstrap_status_field model)"
[[ -n "$model" ]] || return 1
if _ods_cli_bootstrap_upgrade_process_running "$model"; then
return 1
fi
env_model="$(_env_get_raw GGUF_FILE)"
[[ "$env_model" == "$model" ]] || return 1
model_path="$INSTALL_DIR/data/models/$model"
[[ -f "$model_path" ]] || return 1
expected_bytes="$(_ods_cli_bootstrap_status_number bytesTotal)"
if [[ "$expected_bytes" =~ ^[0-9]+$ ]] && (( expected_bytes > 0 )); then
actual_bytes="$(_ods_cli_file_size "$model_path")"
[[ "$actual_bytes" =~ ^[0-9]+$ ]] || return 1
(( actual_bytes >= expected_bytes )) || return 1
fi
return 0
}
_ods_cli_bootstrap_download_near_swap() {
local model percent percent_int downloaded total remaining threshold
model="$(_ods_cli_bootstrap_status_field model)"
[[ -n "$model" ]] || return 1
_ods_cli_bootstrap_upgrade_process_running "$model" || return 1
threshold="${ODS_CLI_BOOTSTRAP_COMPOSE_DOWNLOAD_WAIT_BYTES:-1073741824}"
if ! [[ "$threshold" =~ ^[0-9]+$ ]]; then
threshold=1073741824
fi
downloaded="$(_ods_cli_bootstrap_status_number bytesDownloaded)"
total="$(_ods_cli_bootstrap_status_number bytesTotal)"
if [[ "$downloaded" =~ ^[0-9]+$ && "$total" =~ ^[0-9]+$ ]] && (( total > 0 )); then
remaining=$(( total - downloaded ))
(( remaining < 0 )) && remaining=0
(( remaining <= threshold )) && return 0
fi
percent="$(_ods_cli_bootstrap_status_number percent)"
percent_int="${percent%%.*}"
if [[ "$percent_int" =~ ^[0-9]+$ ]] && (( percent_int >= 95 )); then
return 0
fi
return 1
}
_ods_cli_wait_for_bootstrap_compose_safe() {
local action="${1:-service operation}"
local status_file="$INSTALL_DIR/data/bootstrap-status.json"
[[ -f "$status_file" ]] || return 0
local max_wait="${ODS_CLI_BOOTSTRAP_COMPOSE_WAIT_SECONDS:-1800}"
local interval="${ODS_CLI_BOOTSTRAP_COMPOSE_WAIT_INTERVAL:-5}"
if ! [[ "$max_wait" =~ ^[0-9]+$ ]] || (( max_wait < 0 )); then
max_wait=1800
fi
if ! [[ "$interval" =~ ^[0-9]+$ ]] || (( interval < 1 )); then
interval=5
fi
local waited=0 announced=false status=""
while true; do
status="$(_ods_cli_bootstrap_status)"
case "$status" in
downloading)
if _ods_cli_bootstrap_active_status_settled "$status"; then
if [[ "$announced" == "true" ]]; then
log " Model Upgrade: stale $status status already settled; continuing with $action"
else
warn "Model upgrade status is stale ($status) but the full model is already configured; continuing with $action."
fi
return 0
fi
if ! _ods_cli_bootstrap_download_near_swap; then
log " Model Upgrade: downloading in background; continuing with $action before hot-swap begins"
return 0
fi
if [[ "$announced" == "false" ]]; then
log " Model Upgrade: download nearly complete; waiting before $action touches llama-server"
announced=true
fi
if (( waited >= max_wait )); then
warn "Model upgrade is still $status after ${max_wait}s; refusing to run $action against an active hot-swap."
return 1
fi
sleep "$interval"
waited=$(( waited + interval ))
;;
starting|verifying|swapping)
if _ods_cli_bootstrap_active_status_settled "$status"; then
if [[ "$announced" == "true" ]]; then
log " Model Upgrade: stale $status status already settled; continuing with $action"
else
warn "Model upgrade status is stale ($status) but the full model is already configured; continuing with $action."
fi
return 0
fi
if [[ "$announced" == "false" ]]; then
log " Model Upgrade: $status; waiting before $action touches llama-server"
announced=true
fi
if (( waited >= max_wait )); then
warn "Model upgrade is still $status after ${max_wait}s; refusing to run $action against an active hot-swap."
return 1
fi
sleep "$interval"
waited=$(( waited + interval ))
;;
*)
if [[ "$announced" == "true" ]]; then
log " Model Upgrade: ${status:-idle}; continuing with $action"
fi
return 0
;;
esac
done
}
_ods_cli_reload_model_env() {
# A background bootstrap promotion can rewrite these values while a start
# or restart command is waiting. Clear the process snapshot first so a key
# removed from .env cannot keep overriding Docker Compose.
unset GGUF_FILE LLM_MODEL MAX_CONTEXT CTX_SIZE
load_env
}
_get_host_logical_cpus() {
local cores
# nproc and /proc/cpuinfo are Linux-only; on macOS both are absent, so the
# old chain always fell through to 1 and starved the CPU budget whenever
# Docker's own NCPU was unavailable. Probe sysctl (macOS/BSD) between them.
cores=$(nproc 2>/dev/null \
|| sysctl -n hw.logicalcpu 2>/dev/null \
|| grep -c '^processor' /proc/cpuinfo 2>/dev/null \
|| echo "1")
if [[ "$cores" =~ ^[0-9]+$ ]] && [[ "$cores" -gt 0 ]]; then
echo "$cores"
else
echo "1"
fi
}
_get_docker_available_cpus() {
local cores=""
if command -v docker &>/dev/null; then
cores=$(docker info --format '{{.NCPU}}' 2>/dev/null || true)
cores="${cores//[!0-9]/}"
fi
if [[ "$cores" =~ ^[0-9]+$ ]] && [[ "$cores" -gt 0 ]]; then
echo "$cores"
return 0
fi
_get_host_logical_cpus
}
_calculate_llama_cpu_budget() {
local backend="${1:-cpu}"
local available="${2:-$(_get_docker_available_cpus)}"
local desired_limit=8
local desired_reservation=1
case "$backend" in
amd)
desired_limit=16
desired_reservation=4
;;
nvidia|intel|sycl)
desired_limit=16
desired_reservation=2
;;
apple)
desired_limit=8
desired_reservation=2
;;
esac
if ! [[ "$available" =~ ^[0-9]+$ ]] || [[ "$available" -lt 1 ]]; then
available=1
fi
local limit="$desired_limit"
local reservation="$desired_reservation"
[[ "$available" -lt "$limit" ]] && limit="$available"
[[ "$reservation" -gt "$limit" ]] && reservation="$limit"
echo "$limit $reservation $available"
}
_select_auto_cpu_value() {
local existing="$1" detected="$2"
if [[ "$existing" =~ ^[0-9]+([.][0-9]+)?$ ]] && LC_ALL=C awk "BEGIN { exit !($existing > 0 && $existing <= $detected) }"; then
echo "$existing"
else
echo "$detected"
fi
}
_cap_cpu_value() {
local desired="$1" ceiling="$2"
LC_ALL=C awk -v desired="$desired" -v ceiling="$ceiling" '
BEGIN {
if (ceiling <= 0) ceiling = 1
value = desired
if (value > ceiling) value = ceiling
if (value < 0.01) value = 0.01
printf "%.1f", value
}'
}
_ensure_service_cpu_pair() {
local available="$1" name="$2" desired_limit="$3" desired_reservation="$4"
local limit_key="${name}_CPU_LIMIT"
local reservation_key="${name}_CPU_RESERVATION"
local detected_limit detected_reservation current_limit current_reservation final_limit final_reservation
detected_limit="$(_cap_cpu_value "$desired_limit" "$available")"
current_limit="$(_env_get_raw "$limit_key")"
final_limit="$(_select_auto_cpu_value "$current_limit" "$detected_limit")"
detected_reservation="$(_cap_cpu_value "$desired_reservation" "$final_limit")"
current_reservation="$(_env_get_raw "$reservation_key")"
final_reservation="$(_select_auto_cpu_value "$current_reservation" "$detected_reservation")"
if LC_ALL=C awk "BEGIN { exit !($final_reservation > $final_limit) }"; then
final_reservation="$final_limit"
fi
if [[ "$current_limit" != "$final_limit" ]]; then
_env_set "$limit_key" "$final_limit"
SERVICE_CPU_BUDGET_CHANGED=true
fi
if [[ "$current_reservation" != "$final_reservation" ]]; then
_env_set "$reservation_key" "$final_reservation"
SERVICE_CPU_BUDGET_CHANGED=true
fi
}
ensure_llama_cpu_budget() {
local env_file="$INSTALL_DIR/.env"
[[ -f "$env_file" ]] || return 0
local backend
backend="$(_env_get_raw "GPU_BACKEND")"
backend=$(echo "${backend:-cpu}" | tr '[:upper:]' '[:lower:]')
[[ "$backend" == "none" ]] && backend="cpu"
local limit_raw reservation_raw available
read -r limit_raw reservation_raw available <<< "$(_calculate_llama_cpu_budget "$backend")"
local detected_limit="${limit_raw}.0"
local detected_reservation="${reservation_raw}.0"
local current_limit current_reservation final_limit final_reservation
current_limit="$(_env_get_raw "LLAMA_CPU_LIMIT")"
current_reservation="$(_env_get_raw "LLAMA_CPU_RESERVATION")"
final_limit="$(_select_auto_cpu_value "$current_limit" "$detected_limit")"
final_reservation="$(_select_auto_cpu_value "$current_reservation" "$detected_reservation")"
if LC_ALL=C awk "BEGIN { exit !($final_reservation > $final_limit) }"; then
final_reservation="$final_limit"
fi
local changed=false
if [[ "$current_limit" != "$final_limit" ]]; then
_env_set "LLAMA_CPU_LIMIT" "$final_limit"
changed=true
fi
if [[ "$current_reservation" != "$final_reservation" ]]; then
_env_set "LLAMA_CPU_RESERVATION" "$final_reservation"
changed=true
fi
if [[ "$changed" == "true" ]]; then
log "Auto-adjusted llama-server CPU budget: limit=${final_limit}, reservation=${final_reservation} (Docker CPUs: ${available})"
fi
SERVICE_CPU_BUDGET_CHANGED=false
_ensure_service_cpu_pair "$available" "TTS" "8.0" "2.0"
_ensure_service_cpu_pair "$available" "WHISPER" "4.0" "1.0"
_ensure_service_cpu_pair "$available" "HERMES" "4.0" "0.5"
_ensure_service_cpu_pair "$available" "COMFYUI" "16.0" "2.0"
if [[ "$SERVICE_CPU_BUDGET_CHANGED" == "true" ]]; then
log "Auto-adjusted bundled service CPU budgets (Docker CPUs: ${available})"
fi
unset SERVICE_CPU_BUDGET_CHANGED
}
check_install() {
if [[ ! -d "$INSTALL_DIR" ]]; then
error "ODS not found at $INSTALL_DIR. Set ODS_HOME or run installer first."
fi
if [[ ! -f "$INSTALL_DIR/docker-compose.base.yml" ]]; then
# Backward compat: check for monolithic docker-compose.yml
if [[ ! -f "$INSTALL_DIR/docker-compose.yml" ]]; then
error "docker-compose.base.yml not found in $INSTALL_DIR"
fi
fi
}
# Extract the major component of a semver string (e.g. "2.1.0" → "2").
# Used only for counting major-version jumps; not for ordering comparisons.
_semver_major() {
echo "${1%%.*}"
}
# Full 3-component semver less-than: returns 0 (true) if v1 < v2.
# Strips any leading "v" and ignores pre-release suffixes.
_semver_lt() {
local v1="${1#v}" v2="${2#v}"
local IFS='.'
local -a a=($v1) b=($v2)
local i
for i in 0 1 2; do
local n1="${a[$i]:-0}" n2="${b[$i]:-0}"
n1="${n1%%[!0-9]*}" n2="${n2%%[!0-9]*}"
if (( n1 < n2 )); then return 0; fi
if (( n1 > n2 )); then return 1; fi
done
return 1 # equal → not less-than
}
# Read a top-level or nested string field from a JSON file.
# Usage: _manifest_field <file> <field> e.g. _manifest_field manifest.json ods_version
# Logs a warning to stderr on parse failure rather than silently returning empty.
_manifest_field() {
local file="$1" field="$2" value=""
if [[ ! -f "$file" ]]; then
warn "_manifest_field: file not found: ${file}" >&2
return 1
fi
if command -v jq &>/dev/null; then
if ! value=$(jq -r --arg f "$field" '.[$f] // .release.version // empty' "$file"); then
warn "_manifest_field: jq failed to parse ${file}" >&2
fi
fi
if [[ -z "$value" ]] && command -v python3 &>/dev/null; then
# Pass file and field as argv to avoid shell-injection via string interpolation.
if ! value=$(python3 -c '
import json, sys
try:
d = json.load(open(sys.argv[1]))
f = sys.argv[2]
print(d.get(f) or d.get("release", {}).get("version") or "")
except Exception as e:
sys.stderr.write("_manifest_field: " + str(e) + "\n")
' "$file" "$field"); then
warn "_manifest_field: python3 failed to parse ${file}" >&2
fi
fi
echo "$value"
}
# Version compatibility check for ods update.
# Returns 0 (ok) or 1 (user aborted / hard-blocked).
# Sets _COMPAT_INSTALLED_VER and _COMPAT_TARGET_VER as side-effects.
#
# Version source precedence (single source of truth policy):
# installed: ODS_VERSION in .env > .version file > manifest.json ods_version
# target: manifest.json ods_version (post-pull reflects the incoming release)
_check_version_compat() {
local force="${1:-false}"
# 1. Installed version
# `|| true` preserves the tolerant fallback semantics required by
# the maintainer audit on PR #998: under `set -euo pipefail`,
# a fresh install whose .env lacks ODS_VERSION must fall back
# to .version / manifest.json (handled below), not exit out of
# the surrounding command. Landed on main via #1008.
_COMPAT_INSTALLED_VER=$(grep '^ODS_VERSION=' "$INSTALL_DIR/.env" 2>/dev/null \
| sed -n '1p' | cut -d= -f2 | tr -d '[:space:]' || true)
# Fall back to .version file (written by ods-update.sh / PR #349 convention)
if [[ -z "$_COMPAT_INSTALLED_VER" && -f "$INSTALL_DIR/.version" ]]; then
_COMPAT_INSTALLED_VER=$(jq -r '.version // empty' "$INSTALL_DIR/.version" 2>/dev/null \
|| grep -o '"version"[[:space:]]*:[[:space:]]*"[^"]*"' \
"$INSTALL_DIR/.version" 2>/dev/null | cut -d'"' -f4 \
|| true)
fi
if [[ -z "$_COMPAT_INSTALLED_VER" && -f "$INSTALL_DIR/manifest.json" ]]; then
_COMPAT_INSTALLED_VER=$(_manifest_field "$INSTALL_DIR/manifest.json" "ods_version")
fi
[[ -z "$_COMPAT_INSTALLED_VER" ]] && _COMPAT_INSTALLED_VER="$VERSION"
# 2. Target version — from manifest.json (reflects the incoming release after pull)
_COMPAT_TARGET_VER=""
if [[ -f "$INSTALL_DIR/manifest.json" ]]; then
_COMPAT_TARGET_VER=$(_manifest_field "$INSTALL_DIR/manifest.json" "ods_version")
fi
# 3. min_compatible_ods_version — read via _manifest_field to avoid 2>/dev/null + injection
local min_compat_ver=""
if [[ -f "$INSTALL_DIR/manifest.json" ]]; then
min_compat_ver=$(_manifest_field "$INSTALL_DIR/manifest.json" "min_compatible_ods_version")
fi
# Skip checks if we can't determine versions
if [[ -z "$_COMPAT_INSTALLED_VER" || -z "$_COMPAT_TARGET_VER" ]]; then
return 0
fi
# Skip if installed == target (no actual update)
[[ "$_COMPAT_INSTALLED_VER" == "$_COMPAT_TARGET_VER" ]] && return 0
local cur_major new_major
cur_major=$(_semver_major "$_COMPAT_INSTALLED_VER")
new_major=$(_semver_major "$_COMPAT_TARGET_VER")
# major_jump may be negative (downgrade); use arithmetic not regex for sign-aware logic
local major_jump=$(( new_major - cur_major ))
# 4. Downgrade detection — warn and confirm before proceeding
if (( major_jump < 0 )); then
echo ""
echo -e "${YELLOW}┌──────────────────────────────────────────────────────────┐${NC}"
echo -e "${YELLOW}│ Downgrade detected │${NC}"
echo -e "${YELLOW}└──────────────────────────────────────────────────────────┘${NC}"
echo ""
warn "Installed : v${_COMPAT_INSTALLED_VER} (major ${cur_major})"
warn "Target : v${_COMPAT_TARGET_VER} (major ${new_major})"
echo ""
log "Downgrading may corrupt data or break your installation."
log "Consider restoring a backup instead: ods rollback"
echo ""
if [[ "$force" == "true" ]]; then
warn "--force specified: proceeding with downgrade."
else
read -p " Proceed with downgrade? [y/N] " -n 1 -r || REPLY=""
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
log "Update cancelled."
return 1
fi
fi
echo ""
fi
# 5. Hard block: installed version is below min_compatible_ods_version.
# Uses full 3-component comparison — major-only was insufficient
# (e.g. 1.2.0 vs min 1.5.0 both have major 1 but 1.2.0 < 1.5.0).
if [[ -n "$min_compat_ver" ]] && _semver_lt "$_COMPAT_INSTALLED_VER" "$min_compat_ver"; then
echo ""
echo -e "${RED}╔══════════════════════════════════════════════════════════╗${NC}"
echo -e "${RED}║ UPGRADE BLOCKED — installed version is too old ║${NC}"
echo -e "${RED}╚══════════════════════════════════════════════════════════╝${NC}"
echo ""
warn "Installed : v${_COMPAT_INSTALLED_VER}"
warn "Target : v${_COMPAT_TARGET_VER}"
warn "Minimum : v${min_compat_ver} (min_compatible_ods_version)"
echo ""
log "Your installation is below the minimum supported upgrade version."
log "Upgrade incrementally: first update to v${min_compat_ver}, then re-run."
log "See CHANGELOG.md for migration steps."
echo ""
if [[ "$force" == "true" ]]; then
warn "--force specified: proceeding despite compatibility block. DATA LOSS RISK."
else
log "Use 'ods update --force' to override (not recommended)."
return 1
fi
fi
# 6. Warn: major version jump > 1
if (( major_jump > 1 )); then
echo ""
echo -e "${YELLOW}┌──────────────────────────────────────────────────────────┐${NC}"
echo -e "${YELLOW}│ Major version jump detected │${NC}"
echo -e "${YELLOW}└──────────────────────────────────────────────────────────┘${NC}"
echo ""
warn "Installed : v${_COMPAT_INSTALLED_VER} (major ${cur_major})"
warn "Target : v${_COMPAT_TARGET_VER} (major ${new_major})"
warn "Jump : ${major_jump} major versions"
echo ""
log "Skipping more than 1 major version may introduce breaking changes."
log "Recommended: upgrade step-by-step (v${cur_major} → v$((cur_major+1)) → … → v${new_major})."
log "Review CHANGELOG.md for each major version before proceeding."
echo ""
if [[ "$force" == "true" ]]; then
warn "--force specified: skipping confirmation."
else
read -p " Proceed with v${_COMPAT_INSTALLED_VER} → v${_COMPAT_TARGET_VER} anyway? [y/N] " -n 1 -r || REPLY=""
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
log "Update cancelled."
return 1
fi
warn "Proceeding — back up your data first: ods backup"
fi
echo ""
fi
return 0
}
#=============================================================================
# Safe .env loading (no eval; use lib/safe-env.sh)
#=============================================================================
[[ -f "$SCRIPT_DIR/lib/safe-env.sh" ]] && . "$SCRIPT_DIR/lib/safe-env.sh"
load_env() {
[[ -f "$INSTALL_DIR/.env" ]] || { warn ".env not found at $INSTALL_DIR — run installer first"; return 1; }
load_env_file "$INSTALL_DIR/.env"
}
#=============================================================================
# Service Registry
#=============================================================================
. "$SCRIPT_DIR/lib/service-registry.sh"
# Resolve a user-provided service name to a compose service ID
resolve_service() {
local resolved
resolved=$(sr_resolve "$1")
echo "$resolved"
}
# Regenerate .compose-flags after enable/disable
_regenerate_compose_flags() {
if [[ -x "$INSTALL_DIR/scripts/resolve-compose-stack.sh" ]]; then
# --gpu-count gates the multigpu-{backend}.yml overlay; without it,
# toggling any extension would silently strip multi-GPU plumbing
# from the persisted cache.
# Capture the resolver's stderr instead of discarding it: it reports
# actionable causes (e.g. missing PyYAML) that would otherwise only
# surface commands later as compose's "no configuration file provided".
local resolver_err=""
if ! resolver_err=$("$INSTALL_DIR/scripts/resolve-compose-stack.sh" \
--script-dir "$INSTALL_DIR" --tier "${TIER:-1}" --gpu-backend "${GPU_BACKEND:-nvidia}" \
--gpu-count "${GPU_COUNT:-1}" --ods-mode "${ODS_MODE:-local}" \
2>&1 > "$INSTALL_DIR/.compose-flags"); then
rm -f "$INSTALL_DIR/.compose-flags"
warn "Could not regenerate the compose stack cache. 'ods start' will fail until this is resolved:"
[[ -n "$resolver_err" ]] && printf '%s\n' "$resolver_err" >&2
elif [[ "$resolver_err" == *WARNING:* ]]; then
# The stack resolved, but refused extension files (and anything
# that depends on them) were left out. Say which, and why.
printf '%s\n' "$resolver_err" | grep '^WARNING:' >&2 || true
fi
else
rm -f "$INSTALL_DIR/.compose-flags"
fi
}
# Run a lifecycle hook for a service (reads manifest directly via Python)
_run_hook() {
local service_id="$1" hook_name="$2"
local ext_dir="$INSTALL_DIR/extensions/services/$service_id"
# Also check user-extensions
[[ -d "$ext_dir" ]] || ext_dir="$INSTALL_DIR/data/user-extensions/$service_id"
[[ -d "$ext_dir" ]] || return 0
local hook_path
hook_path=$(python3 - "$ext_dir" "$hook_name" <<'PYEOF'
import yaml, sys
from pathlib import Path
ext_dir = Path(sys.argv[1])
hook_name = sys.argv[2]
manifest_path = None
for name in ("manifest.yaml", "manifest.yml"):
candidate = ext_dir / name
if candidate.exists():
manifest_path = candidate
break
if manifest_path is None:
sys.exit(0)
with open(manifest_path) as f:
m = yaml.safe_load(f)
if not isinstance(m, dict):
sys.exit(0)
service = m.get("service", {})
if not isinstance(service, dict):
sys.exit(0)
# Check hooks map first
hooks = service.get("hooks", {})
hook_script = ""
if isinstance(hooks, dict):
hook_script = hooks.get(hook_name, "")
# Fallback: setup_hook -> post_install only
if not hook_script and hook_name == "post_install":
hook_script = service.get("setup_hook", "")
if not hook_script:
sys.exit(0)
# Validate path containment
hook_path = (ext_dir / hook_script).resolve()
try:
hook_path.relative_to(ext_dir.resolve())
except ValueError:
print(f"ERROR: hook path escapes extension directory: {hook_script}", file=sys.stderr)
sys.exit(1)
if not hook_path.is_file():
sys.exit(0)
print(str(hook_path))
PYEOF
) || return 0
[[ -z "$hook_path" || ! -f "$hook_path" ]] && return 0
log "Running $hook_name hook for $service_id..."
SERVICE_ID="$service_id" \
SERVICE_PORT="${SERVICE_PORTS[$service_id]:-0}" \
SERVICE_DATA_DIR="$INSTALL_DIR/data/$service_id" \
ODS_VERSION="$VERSION" \
GPU_BACKEND="${GPU_BACKEND:-}" \
HOOK_NAME="$hook_name" \
bash "$hook_path" "$INSTALL_DIR" "${GPU_BACKEND:-}" \
|| warn "$hook_name hook failed for $service_id (non-fatal)"
}
# Build full compose flags: base + GPU overlay + enabled extensions
get_compose_flags() {
_ensure_hermes_dashboard_session_token
# Fast path: use saved flags from installer if available
if [[ -f "$INSTALL_DIR/.compose-flags" ]]; then
local cached
cached=$(< "$INSTALL_DIR/.compose-flags")
if [[ "$cached" == -f\ * ]]; then
# Validate that every referenced compose file still exists.
# Protects against renames across upgrades (e.g. multigpu.yml →
# multigpu-nvidia.yml) where the cache would otherwise hand docker
# compose a path that no longer resolves.
local stale=0 prev="" tok
for tok in $cached; do
if [[ "$prev" == "-f" ]]; then
if [[ "$tok" = /* ]]; then
[[ -f "$tok" ]] || { stale=1; break; }
else
[[ -f "$INSTALL_DIR/$tok" ]] || { stale=1; break; }
fi
fi
prev="$tok"
done
local _ods_mode="${ODS_MODE:-local}"
# An ODS-managed llama-server outside the stack (Windows Portal).
local _host_native_active="false"
[[ -n "${NATIVE_LLM_BASE_URL:-}" && "$_ods_mode" != "cloud" ]] && _host_native_active="true"
if [[ "$_ods_mode" == "cloud" ]] && \
{ [[ "$cached" == *"docker-compose.cpu.yml"* ]] || [[ "$cached" == *"compose.local.yaml"* ]] || [[ "$cached" != *"docker-compose.cloud.yml"* ]]; }; then
stale=1
fi
if [[ "$_host_native_active" == "true" ]] && \
{ [[ "$cached" == *"compose.local.yaml"* ]] || [[ "$cached" == *"docker-compose.amd.yml"* ]] || [[ "$cached" == *"docker-compose.cloud.yml"* ]] || [[ "$cached" != *"docker-compose.host-native-llm.yml"* ]]; }; then
stale=1
fi
if [[ "$_host_native_active" != "true" ]] && [[ "$cached" == *"docker-compose.host-native-llm.yml"* ]]; then
stale=1
fi
if [[ "$_ods_mode" != "cloud" ]] && [[ "$cached" == *"docker-compose.cloud.yml"* ]]; then
stale=1
fi
# The retired Lemonade overlay can outlive an update that kept
# the old file on disk; the stack must be resolved again.
if [[ "$cached" == *"docker-compose.lemonade-external.yml"* ]]; then
stale=1
fi
# The AMD image follows AMD_INFERENCE_BACKEND (vulkan or rocm).
if [[ "$cached" == *"docker-compose.amd.yml"* ]]; then
if [[ "${AMD_INFERENCE_BACKEND:-vulkan}" == "rocm" ]]; then
[[ "$cached" == *"docker-compose.amd-rocm.yml"* ]] || stale=1
else
[[ "$cached" != *"docker-compose.amd-rocm.yml"* ]] || stale=1
fi
fi
if [[ "$stale" == "0" ]]; then
if [[ "$cached" == *user-extensions* || -d "$INSTALL_DIR/data/user-extensions" ]]; then
local policy="$INSTALL_DIR/scripts/compose-cache-policy.py"
[[ -f "$policy" ]] || { warn "Saved extensions need the Compose security validator; repair ODS."; return 1; }
local policy_python="${ODS_PYTHON_CMD:-python3}"
if [[ -f "$INSTALL_DIR/lib/python-cmd.sh" ]]; then
policy_python="$(. "$INSTALL_DIR/lib/python-cmd.sh"; ods_detect_python_cmd_with_module yaml)" || return 1
fi
"$policy_python" "$policy" --install-dir "$INSTALL_DIR" --flags="$cached" --format flags
return $?
fi
echo "$cached"
return
fi
fi
# Stale or corrupt — remove and fall through to dynamic resolution
rm -f "$INSTALL_DIR/.compose-flags"
fi
# Fallback: resolve dynamically
local base_flags
if [[ -x "$INSTALL_DIR/scripts/resolve-compose-stack.sh" ]]; then
# Resolver handles base + GPU overlay + extension compose files.
# --gpu-count gates the multigpu-{backend}.yml overlay — without it,
# this fallback path resolves to a single-GPU stack on multi-GPU hosts.
base_flags=$("$INSTALL_DIR/scripts/resolve-compose-stack.sh" \
--script-dir "$INSTALL_DIR" --tier "${TIER:-1}" --gpu-backend "${GPU_BACKEND:-nvidia}" \
--gpu-count "${GPU_COUNT:-1}" --ods-mode "${ODS_MODE:-local}")
echo "$base_flags"
elif [[ -f "$INSTALL_DIR/docker-compose.base.yml" ]]; then
base_flags="-f docker-compose.base.yml"
local ext_flags
ext_flags=$(sr_compose_flags)
echo "$base_flags $ext_flags"
else
base_flags="-f docker-compose.yml"
local ext_flags
ext_flags=$(sr_compose_flags)
echo "$base_flags $ext_flags"
fi
}
# Run `docker compose <args...>` with a compact summary on success and a
# surfaced error banner on failure.
#
# Usage: _compose_run_with_summary <verb> <compose_args...>
# <verb> Human-readable gerund phrase, e.g. "Restarting all services"
# <compose_args> Everything that goes after `docker compose`, including