Repository navigation
Expand file tree
/
Copy pathopencode.sh
More file actions
executable file
·999 lines (881 loc) · 32.4 KB
/
Copy pathopencode.sh
File metadata and controls
executable file
·999 lines (881 loc) · 32.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
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
# Rootless Podman API socket on the host. The container talks to the host's
# user-level Podman through this socket (never a privileged daemon).
PODMAN_SOCKET="${PODMAN_SOCKET:-${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/podman/podman.sock}"
PROJECT_DIR="$(realpath "$(pwd)")"
VERSION_FILE="${SCRIPT_DIR}/.opencode-version"
OPENCODE_DIR="${SCRIPT_DIR}/.opencode"
OPENCODE_BASHRC="${OPENCODE_DIR}/.bashrc"
OPENCODE_VERSION="${OPENCODE_VERSION:-latest}"
# One key per absolute project path (shared state would leak A↔B).
project_key_for_dir() {
printf '%s' "$1" | sha256sum | awk '{print $1}'
}
# One history file per absolute project path (shared history would leak A↔B).
history_file_for_project() {
local project_dir="$1"
local hist_key
hist_key="$(project_key_for_dir "${project_dir}")"
printf '%s\n' "${OPENCODE_DIR}/history/${hist_key}"
}
# Per-project scratch space mounted over the container's entire /tmp so temp
# files persist across sessions and shadow any root-owned files in the image.
tmp_dir_for_project() {
local project_dir="$1"
local tmp_key
tmp_key="$(project_key_for_dir "${project_dir}")"
printf '%s\n' "${OPENCODE_DIR}/tmp/${tmp_key}"
}
# One lock file per project, held by opencode.sh while its container runs.
# flock locks are released by the kernel when the process dies, so a stale
# lock file does not imply a running session.
lock_file_for_project() {
local project_dir="$1"
local lock_key
lock_key="$(project_key_for_dir "${project_dir}")"
printf '%s\n' "${OPENCODE_DIR}/locks/${lock_key}"
}
# True if another opencode.sh session currently holds the project's lock.
project_tmp_in_use() {
local lock_file="$1"
[[ -e "${lock_file}" ]] || return 1
( exec 9>>"${lock_file}"; ! flock -n 9 )
}
# Delete scratch dirs of other projects that have been idle longer than
# OPENCODE_TMP_RETENTION_DAYS (default 14). The current project is never
# pruned here: launching it may be an attempt to resume its last session.
# Dirs without a .last-used marker are kept, since their age is unknown
# (e.g. created by an older version of this script).
prune_stale_project_tmps() {
local current_key="$1" dir key marker last_used now age removed=0
local retention="${OPENCODE_TMP_RETENTION_DAYS:-14}"
[[ "${retention}" =~ ^[0-9]+$ ]] || retention=14
now="$(date +%s)"
for dir in "${OPENCODE_DIR}/tmp/"*/; do
[[ -d "${dir}" ]] || continue
key="$(basename "${dir}")"
[[ "${key}" == "${current_key}" ]] && continue
marker="${dir}.last-used"
[[ -f "${marker}" ]] || continue
last_used="$(stat -c %Y "${marker}")" || continue
age=$(( now - last_used ))
(( age > retention * 86400 )) || continue
project_tmp_in_use "${OPENCODE_DIR}/locks/${key}" && continue
rm -rf -- "${dir}"
removed=$(( removed + 1 ))
done
if (( removed > 0 )); then
echo "→ Pruned ${removed} stale scratch dir(s) idle over ${retention} days"
fi
}
# Record a project path so previous projects can be listed later (mounts and
# history files are keyed by one-way hash, so the real path must be stored).
# Maintains newest-first order with no duplicates.
register_project() {
local project="$1" file tmp
file="${OPENCODE_DIR}/projects"
mkdir -p "${OPENCODE_DIR}"
touch "${file}"
tmp="$(mktemp)"
printf '%s\n' "${project}" > "${tmp}"
grep -vxF "${project}" "${file}" >> "${tmp}" || true
mv "${tmp}" "${file}"
}
get_stored_version() {
if [[ -f "${VERSION_FILE}" ]]; then
cat "${VERSION_FILE}"
fi
}
get_latest_version() {
curl -fsSL https://api.github.com/repos/anomalyco/opencode/releases/latest 2>/dev/null | \
grep -m1 '"tag_name"' | sed 's/.*"tag_name": *"v\?\([^"]*\)".*/\1/'
}
check_for_updates() {
local timeout="${1:-5}"
local result
result=$(curl -fsSL --max-time "${timeout}" https://api.github.com/repos/anomalyco/opencode/releases/latest 2>/dev/null | \
grep -m1 '"tag_name"' | sed 's/.*"tag_name": *"v\?\([^"]*\)".*/\1/' || true)
echo "${result}"
}
show_update_banner() {
local new_version="$1"
echo ""
echo "╔══════════════════════════════════════════════════════════╗"
echo "║ New OpenCode version available! ║"
echo "║ ${new_version} ║"
echo "║ Press any key to continue... ║"
echo "╚══════════════════════════════════════════════════════════╝"
echo ""
if [[ -t 0 ]]; then
read -n 1 -s
else
sleep 1
fi
}
update_version_file() {
local version="$1"
echo "${version}" > "${VERSION_FILE}"
}
require_podman() {
if ! command -v podman >/dev/null 2>&1; then
echo "✗ podman not found; this launcher requires rootless Podman on the host." >&2
exit 1
fi
}
host_podman_version() {
podman --version | awk '{print $NF}'
}
# The container's Podman remote client must match the host's Podman version
# (the libpod remote API is not cross-version compatible).
build_image() {
local podman_version
podman_version="$(host_podman_version)"
echo "→ Building opencode container with Podman remote client v${podman_version}"
podman build -t opencode-fk \
--build-arg OPENCODE_VERSION="${OPENCODE_VERSION}" \
--build-arg UID="$(id -u)" \
--build-arg GID="$(id -g)" \
--build-arg PODMAN_VERSION="${podman_version}" \
-f "${SCRIPT_DIR}/Dockerfile" "${SCRIPT_DIR}"
}
update_opencode() {
local latest
latest=$(check_for_updates)
if [[ -z "${latest}" ]]; then
echo "✗ Could not fetch latest version from GitHub" >&2
exit 1
fi
show_update_banner "${latest}"
OPENCODE_VERSION="${latest}"
echo "→ Updating OpenCode to version ${latest}..."
build_image
update_version_file "${latest}"
echo "✓ Updated to version ${latest}"
}
clean_project_tmp() {
if (( ${#POSITIONAL[@]} > 1 )); then
echo "✗ Usage: opencode.sh clean" >&2
exit 1
fi
local project_dir tmp_dir lock_file marker last_used size
project_dir="$(realpath "$(pwd)")"
tmp_dir="$(tmp_dir_for_project "${project_dir}")"
lock_file="$(lock_file_for_project "${project_dir}")"
if [[ ! -d "${tmp_dir}" ]]; then
echo "→ No scratch space to clean for ${project_dir}"
return
fi
if project_tmp_in_use "${lock_file}"; then
echo "✗ A session for this project is running; stop it before cleaning." >&2
exit 1
fi
marker="${tmp_dir}/.last-used"
if [[ -f "${marker}" ]]; then
last_used="$(date -d "@$(stat -c %Y "${marker}")" '+%Y-%m-%d %H:%M')"
else
last_used="$(date -d "@$(stat -c %Y "${tmp_dir}")" '+%Y-%m-%d %H:%M')"
fi
size="$(du -sh -- "${tmp_dir}" | cut -f1)"
echo "Persistent scratch space for ${project_dir}:"
echo " path: ${tmp_dir}"
echo " size: ${size}"
echo " last used: ${last_used}"
echo ""
if prompt_yn "Delete it? [y/N]" n; then
echo ""
rm -rf -- "${tmp_dir}"
echo "✓ Removed ${tmp_dir}"
else
echo "→ Kept ${tmp_dir}"
fi
}
build_and_run() {
build_image
run_container
}
validate_paths() {
local -a paths=("$@")
local path resolved
for path in "${paths[@]}"; do
resolved="$(realpath "${path}")"
if [[ ! -e "${resolved}" ]]; then
echo "✗ Path does not exist: ${path}" >&2
return 1
fi
done
local -a sorted
mapfile -t sorted < <(printf "%s\n" "${paths[@]}" | sort)
for (( i=1; i<${#sorted[@]}; i++ )); do
if [[ "${sorted[$i]}" == "${sorted[$((i-1))]}" ]]; then
echo "✗ Duplicate path specified: ${sorted[$i]}" >&2
return 1
fi
done
}
run_container() {
echo "→ Starting opencode v${OPENCODE_VERSION}"
local OPENCODE_HISTORY OPENCODE_TMP PROJECT_KEY
OPENCODE_HISTORY="$(history_file_for_project "${PROJECT_DIR}")"
OPENCODE_TMP="$(tmp_dir_for_project "${PROJECT_DIR}")"
PROJECT_KEY="$(project_key_for_dir "${PROJECT_DIR}")"
prune_stale_project_tmps "${PROJECT_KEY}"
mkdir -p "${HOME}/.local/share/opencode/"
mkdir -p "${OPENCODE_DIR}/history"
mkdir -p "${OPENCODE_DIR}/locks"
mkdir -p "${OPENCODE_TMP}"
# Pre-create the nested X11 mountpoint as the host user so Podman does not
# create it as an unmapped subuid inside the persisted scratch directory.
mkdir -p "${OPENCODE_TMP}/.X11-unix"
touch "${OPENCODE_TMP}/.last-used"
touch "${OPENCODE_BASHRC}"
touch "${OPENCODE_HISTORY}"
register_project "${PROJECT_DIR}"
# Hold the lock until this script exits (i.e. until the container stops) so
# clean and prune never delete scratch space of a running session.
exec 9>>"$(lock_file_for_project "${PROJECT_DIR}")"
if ! flock -n 9; then
echo "⚠ Another session for this project is running; /tmp scratch space is shared." >&2
fi
local -a volume_args=(
-v "${PROJECT_DIR}:${PROJECT_DIR}"
-v "${OPENCODE_TMP}:/tmp"
)
# The tooling repo (this script's directory) is always mounted so the
# shared-browser skill and browser-cli/browser.sh are available to every
# project. Deduplicate against PROJECT_DIR and extra mounts.
if [[ "${SCRIPT_DIR}" != "${PROJECT_DIR}" ]]; then
volume_args+=(-v "${SCRIPT_DIR}:${SCRIPT_DIR}")
fi
for path in "${EXTRA_MOUNTS[@]}"; do
[[ "${path}" == "${SCRIPT_DIR}" || "${path}" == "${PROJECT_DIR}" ]] && continue
volume_args+=(-v "${path}:${path}")
done
# Mount the host's resolv.conf: with --network host the podman-generated
# snapshot goes stale when the machine switches networks, which breaks DNS
# in long-lived sessions until the container is recreated.
volume_args+=(
-v /etc/resolv.conf:/etc/resolv.conf:ro
-v "${HOME}/.config/opencode/":/home/dev/.config/opencode/
-v "${HOME}/.local/share/opencode/":/home/dev/.local/share/opencode/
-v "${HOME}/.ssh/config":/home/dev/.ssh/config
-v /tmp/.X11-unix:/tmp/.X11-unix
-v "${HOME}/.grok/":/home/dev/.grok/
-v "${HOME}/.config/opencode/skills":/home/dev/.grok/skills
-v "${OPENCODE_BASHRC}":/home/dev/.bashrc
-v "${OPENCODE_HISTORY}":/home/dev/.bash_history
)
# Mount only the selected per-host SSH socket dirs. The dir (not the
# socket file) is the mount unit, so a master reconnecting later creates a
# fresh socket inode that is visible without restarting the container.
local ssh_dir ssh_rel
for ssh_dir in "${SSH_MOUNT_DIRS[@]}"; do
[[ "${ssh_dir}" == "${HOME}/"* && -d "${ssh_dir}" ]] || continue
ssh_rel="${ssh_dir#"${HOME}"/}"
volume_args+=(--mount "type=bind,src=${ssh_dir},dst=/home/dev/${ssh_rel},ro")
done
# Browser scripts key their container/profile/CDP state by project, so
# per-project OpenCode sessions do not share one Chromium.
local -a env_args=(
-e "DISPLAY=${DISPLAY:-}"
-e "OPENCODE_PROJECT_DIR=${PROJECT_DIR}"
-e "OPENCODE_PROJECT_KEY=${PROJECT_KEY}"
-e "OPENCODE_TOOLING_DIR=${SCRIPT_DIR}"
)
if [[ "${MOUNT_PODMAN}" == true ]]; then
if [[ ! -S "${PODMAN_SOCKET}" ]]; then
echo "✗ Podman API socket not found: ${PODMAN_SOCKET}" >&2
echo " Enable it on the host with: systemctl --user enable --now podman.socket" >&2
exit 1
fi
# Mount at the same path, so paths inside API requests stay valid on the host.
volume_args+=(-v "${PODMAN_SOCKET}:${PODMAN_SOCKET}")
env_args+=(-e "CONTAINER_HOST=unix://${PODMAN_SOCKET}")
fi
# keep-id maps the host user to the same UID/GID inside the container, so
# mounted project files keep their ownership (rootless Podman remaps UIDs).
local -a extra_args=(--userns=keep-id)
if [[ "${MOUNT_KVM}" == true ]]; then
extra_args+=(--device /dev/kvm)
# Rootless Podman cannot grant the host 'kvm' group by GID; keep-groups
# passes the invoking user's supplementary groups into the container.
if id -nG | tr ' ' '\n' | grep -qx kvm; then
extra_args+=(--group-add keep-groups)
else
echo "⚠ Not a member of the host 'kvm' group; /dev/kvm may be inaccessible." >&2
echo " Fix with: sudo usermod -aG kvm ${USER}" >&2
fi
fi
podman run -it --rm \
"${env_args[@]}" \
"${volume_args[@]}" \
-w "${PROJECT_DIR}" \
--network host \
"${extra_args[@]}" \
opencode-fk \
bash -c "exec bash"
}
MOUNT_PODMAN=true
MOUNT_KVM=false
SSH_SOCKETS_MODE=prompt
SSH_MOUNT_DIRS=()
show_help() {
cat <<'EOF'
Usage: opencode.sh [options] [project-dir] [extra-mounts...]
Run OpenCode inside a rootless Podman container.
Options:
--no-podman Do not mount the Podman API socket (default: mounted)
--kvm Mount /dev/kvm for hardware-accelerated virtualization
(requires membership in the host 'kvm' group)
--no-ssh Do not mount SSH ControlMaster socket dirs
--pick-ssh Choose which SSH host socket dirs to mount
-h, --help Show this help message and exit
SSH host socket dirs are discovered from ControlPath values in ~/.ssh/config.
The previous selection for this project is reused after a Y/n prompt; answer
n to choose a different set of hosts.
Commands:
update Build/update the container image to the latest version
clean Delete this project's persistent /tmp scratch space
project-dir Path to the project to open (default: current dir)
extra-mounts... Additional paths to mount into the container
EOF
}
parse_flags() {
local args=()
for arg in "$@"; do
case "${arg}" in
--no-podman|--no-docker)
MOUNT_PODMAN=false
;;
--kvm)
MOUNT_KVM=true
;;
--no-ssh)
SSH_SOCKETS_MODE=none
;;
--pick-ssh)
SSH_SOCKETS_MODE=pick
;;
-h|--help)
show_help
exit 0
;;
-*)
echo "✗ Unknown option: ${arg}" >&2
show_help >&2
exit 1
;;
*)
args+=("${arg}")
;;
esac
done
POSITIONAL=("${args[@]}")
}
main() {
parse_flags "$@"
if [[ "${POSITIONAL[0]:-}" == "clean" ]]; then
clean_project_tmp
return
fi
require_podman
if [[ "${POSITIONAL[0]:-}" == "update" ]]; then
update_opencode
return
fi
case "${#POSITIONAL[@]}" in
0)
PROJECT_DIR="$(realpath "$(pwd)")"
EXTRA_MOUNTS=()
;;
*)
PROJECT_DIR="$(realpath "${POSITIONAL[0]}")"
mapfile -t EXTRA_MOUNTS < <(resolve_extra_mounts "${POSITIONAL[@]:1}")
;;
esac
apply_mount_memory
apply_ssh_socket_selection
if ! validate_paths "${PROJECT_DIR}" "${EXTRA_MOUNTS[@]}"; then
exit 1
fi
check_and_run
}
check_and_run() {
local stored latest
stored=$(get_stored_version)
latest=$(check_for_updates 1)
if [[ -n "${latest}" && "${latest}" != "${stored}" ]]; then
show_update_banner "${latest}"
fi
if [[ -n "${stored}" ]]; then
OPENCODE_VERSION="${stored}"
run_container
else
if [[ -z "${latest}" ]]; then
echo "→ First run: no stored version found, fetching latest..."
latest=$(get_latest_version)
fi
OPENCODE_VERSION="${latest}"
build_and_run
update_version_file "${latest}"
fi
}
resolve_extra_mounts() {
local path resolved
for path in "$@"; do
resolved="$(realpath "${path}")"
echo "${resolved}"
done
}
# One memory file per absolute project path (mirrors history_file_for_project).
mounts_file_for_project() {
local project_dir="$1"
local key
key="$(project_key_for_dir "${project_dir}")"
printf '%s\n' "${OPENCODE_DIR}/mounts/${key}"
}
# Load extra mounts for a project into the global MEM_MOUNTS array.
# Returns 0 if a memory file for the project exists, 1 otherwise.
get_mem_mounts() {
local project="$1" file
MEM_MOUNTS=()
file="$(mounts_file_for_project "${project}")"
[[ -f "${file}" ]] || return 1
mapfile -t MEM_MOUNTS < "${file}"
}
# Save extra mounts for a project (one per line). Removes the file if empty.
save_mem_mounts() {
local project="$1" file tmp
shift
file="$(mounts_file_for_project "${project}")"
mkdir -p "$(dirname "${file}")"
if (( $# > 0 )); then
tmp="$(mktemp)"
printf '%s\n' "$@" > "${tmp}"
mv "${tmp}" "${file}"
else
rm -f "${file}"
fi
}
# Remove the memory file for a project.
clear_mem_mounts() {
local project="$1" file
file="$(mounts_file_for_project "${project}")"
rm -f "${file}"
}
# True if the two referenced arrays contain the same members regardless of order.
sets_equal() {
local -n _a="$1" _b="$2"
local -a sa=() sb=()
if (( ${#_a[@]} > 0 )); then
mapfile -t sa < <(printf '%s\n' "${_a[@]}" | sort -u)
fi
if (( ${#_b[@]} > 0 )); then
mapfile -t sb < <(printf '%s\n' "${_b[@]}" | sort -u)
fi
[[ "${sa[*]}" == "${sb[*]}" ]]
}
# Prompt for Y/n. Defaults to ${2:-y}; non-interactive input takes the default.
prompt_yn() {
local prompt="$1" default="${2:-y}" answer
while true; do
if ! [[ -t 0 ]]; then
[[ "${default}" =~ ^[yY]$ ]] && return 0 || return 1
fi
printf '%s ' "${prompt}"
IFS= read -r answer
case "${answer}" in
'' )
[[ "${default}" =~ ^[yY]$ ]] && return 0 || return 1
;;
y|Y) return 0 ;;
n|N) return 1 ;;
*) echo "Please answer y or n." >&2 ;;
esac
done
}
# Print an array, one item per line.
show_mount_list() {
local -n _list="$1"
local item
for item in "${_list[@]}"; do
printf ' %s\n' "${item}"
done
}
# Print only the genuine additions/removals between the newly-passed and
# memorized extra mounts (items present in both sets are unchanged, not listed).
show_mount_diff() {
local -n _new="$1" _old="$2"
local item other found
local -a added=() removed=()
for item in "${_new[@]}"; do
found=0
for other in "${_old[@]}"; do
[[ "${item}" == "${other}" ]] && { found=1; break; }
done
(( found )) || added+=("${item}")
done
for item in "${_old[@]}"; do
found=0
for other in "${_new[@]}"; do
[[ "${item}" == "${other}" ]] && { found=1; break; }
done
(( found )) || removed+=("${item}")
done
if (( ${#added[@]} > 0 )); then
echo " added:"
for item in "${added[@]}"; do
printf ' + %s\n' "${item}"
done
fi
if (( ${#removed[@]} > 0 )); then
echo " removed:"
for item in "${removed[@]}"; do
printf ' - %s\n' "${item}"
done
fi
}
# Resolve mount memory: reuse, save, prompt, or clear based on the current invocation.
apply_mount_memory() {
local -a reuse=()
if get_mem_mounts "${PROJECT_DIR}"; then
# Memory exists for this project.
if (( ${#EXTRA_MOUNTS[@]} > 0 )); then
# 2+ dirs passed.
if sets_equal EXTRA_MOUNTS MEM_MOUNTS; then
return 0
fi
show_mount_diff EXTRA_MOUNTS MEM_MOUNTS
if prompt_yn "use new mounts [Y/n]" y; then
save_mem_mounts "${PROJECT_DIR}" "${EXTRA_MOUNTS[@]}"
else
EXTRA_MOUNTS=( "${MEM_MOUNTS[@]}" )
fi
else
# 0 or 1 dir passed: offer to reuse the memorized mounts.
reuse=( "${PROJECT_DIR}" "${MEM_MOUNTS[@]}" )
show_mount_list reuse
if prompt_yn "reuse mounts [Y/n]" y; then
EXTRA_MOUNTS=( "${MEM_MOUNTS[@]}" )
else
clear_mem_mounts "${PROJECT_DIR}"
fi
fi
elif (( ${#EXTRA_MOUNTS[@]} > 0 )); then
# No memory yet for this project: silently save when 2+ dirs are passed.
save_mem_mounts "${PROJECT_DIR}" "${EXTRA_MOUNTS[@]}"
fi
}
# One memory file per project for the SSH socket dirs exposed to the
# container. Stores only directory basenames under ~/.ssh/sockets.
ssh_sockets_file_for_project() {
local project_dir="$1"
local key
key="$(project_key_for_dir "${project_dir}")"
printf '%s\n' "${OPENCODE_DIR}/ssh-sockets/${key}"
}
# Load the project's remembered SSH socket dir names into MEM_SSH_DIRS.
# Returns 0 if a memory file exists; an empty file means "mount none".
get_mem_ssh_dirs() {
local file
MEM_SSH_DIRS=()
file="$(ssh_sockets_file_for_project "$1")"
[[ -f "${file}" ]] || return 1
mapfile -t MEM_SSH_DIRS < "${file}"
}
# Save SSH socket dir names for a project. An empty list is stored as an empty
# file so "deliberately none" is not prompted again on every start.
save_mem_ssh_dirs() {
local project="$1" file tmp
shift
file="$(ssh_sockets_file_for_project "${project}")"
mkdir -p "$(dirname "${file}")"
if (( $# > 0 )); then
tmp="$(mktemp)"
printf '%s\n' "$@" > "${tmp}"
mv "${tmp}" "${file}"
else
: > "${file}"
fi
}
# Expand a leading ~/ (older OpenSSH versions may not expand it in ssh -G).
expand_home_path() {
case "$1" in
"~/"*) printf '%s/%s\n' "${HOME}" "${1#\~/}" ;;
"~") printf '%s\n' "${HOME}" ;;
*) printf '%s\n' "$1" ;;
esac
}
# Host aliases declared in ~/.ssh/config. Wildcard/negated patterns are
# skipped; Include files are not followed.
ssh_config_host_aliases() {
local conf="${HOME}/.ssh/config" line word
local -a words
[[ -f "${conf}" ]] || return 1
while IFS= read -r line; do
[[ "${line}" =~ ^[[:space:]]*[Hh][Oo][Ss][Tt][[:space:]]+(.*)$ ]] || continue
read -r -a words <<< "${BASH_REMATCH[1]}"
for word in "${words[@]}"; do
if [[ "${word}" == *'*'* || "${word}" == *'?'* || "${word}" == '!'* ]]; then
continue
fi
printf '%s\n' "${word}"
done
done < "${conf}" | awk '!seen[$0]++'
}
# Effective ControlPath for a host alias, with ~ expanded.
ssh_control_path_for_alias() {
local alias="$1" control_path
control_path="$(ssh -G "${alias}" 2>/dev/null | \
awk '$1 == "controlpath" { sub(/^controlpath /, ""); print; exit }')"
[[ -n "${control_path}" && "${control_path}" != "none" ]] || return 1
expand_home_path "${control_path}"
}
# Report whether a control socket is usable: alive, stale, or no master yet.
ssh_socket_state() {
local socket="$1"
if [[ ! -S "${socket}" ]]; then
[[ -e "${socket}" ]] && printf 'stale' || printf 'no master'
return
fi
if ssh -O check -S "${socket}" placeholder >/dev/null 2>&1; then
printf 'alive'
else
printf 'stale'
fi
}
# Discover per-host socket dirs from ~/.ssh/config: a ControlPath under
# ~/.ssh/sockets/<host>/ means <host> is the mountable dir. Mounting the dir
# (instead of the socket file) lets a reconnecting master's new inode show up
# in the container without a restart. Populates the SSH_SOCKET_* arrays.
discover_ssh_socket_dirs() {
local root="${HOME}/.ssh/sockets"
local alias control_path dir
local -A dir_index=() dir_aliases=()
SSH_SOCKET_DIRS=()
SSH_SOCKET_SOCKETS=()
SSH_SOCKET_LABELS=()
SSH_SOCKET_STATES=()
while IFS= read -r alias; do
control_path="$(ssh_control_path_for_alias "${alias}")" || continue
[[ "${control_path}" == "${root}/"* ]] || continue
dir="$(dirname -- "${control_path}")"
# A ControlPath directly in the root is a legacy flat socket file,
# not a mountable per-host dir.
[[ "${dir}" != "${root}" ]] || continue
if [[ -z "${dir_index["${dir}"]:-}" ]]; then
SSH_SOCKET_DIRS+=("${dir}")
SSH_SOCKET_SOCKETS+=("${control_path}")
SSH_SOCKET_STATES+=("$(ssh_socket_state "${control_path}")")
dir_index["${dir}"]="${#SSH_SOCKET_DIRS[@]}"
dir_aliases["${dir}"]="${alias}"
else
dir_aliases["${dir}"]+=", ${alias}"
fi
done < <(ssh_config_host_aliases)
local i
for (( i = 0; i < ${#SSH_SOCKET_DIRS[@]}; i++ )); do
SSH_SOCKET_LABELS+=("${dir_aliases["${SSH_SOCKET_DIRS[$i]}"]}")
done
(( ${#SSH_SOCKET_DIRS[@]} > 0 ))
}
# Create missing per-host socket dirs so ssh can bind its control socket
# there; OpenSSH never creates parent directories itself.
ensure_ssh_socket_dirs() {
local dir
for dir in "${SSH_SOCKET_DIRS[@]}"; do
[[ -d "${dir}" ]] && continue
if [[ -e "${dir}" ]]; then
echo "⚠ Not a directory, cannot use as SSH socket dir: ${dir}" >&2
continue
fi
mkdir -p -m 700 -- "${dir}" || echo "⚠ Cannot create ${dir}" >&2
done
return 0
}
# Multi-select picker over the discovered SSH socket dirs. Args are initially
# ticked dir basenames (the project's remembered set). Sets PICK_SSH_DIRS on
# accept; returns 1 if cancelled or not running on a terminal.
pick_ssh_socket_dirs() {
local -a initial=("$@")
local n="${#SSH_SOCKET_DIRS[@]}"
local i=0 idx key rest name box
local -A ticked=()
local orig interrupted=0 first=1
(( n > 0 )) || return 1
[[ -t 0 && -t 2 ]] || return 1
for name in "${initial[@]}"; do
ticked["${name}"]=1
done
PICK_SSH_DIRS=()
# Same terminal handling as vcopen's project picker.
orig="$(stty -g 2>/dev/null)" || orig=""
stty -echo -icanon min 1 time 0 2>/dev/null || stty -echo
restore_tty() {
if (( !first )); then
printf '\033[%dA\033[J' "${n}" >&2
fi
if [[ -n "${orig}" ]]; then
stty "${orig}" 2>/dev/null || stty echo icanon
else
stty echo icanon 2>/dev/null
fi
echo >&2
}
trap restore_tty EXIT TERM
trap 'interrupted=1' INT
redraw_ssh_picker() {
if (( !first )); then
printf '\033[%dA\033[J' "${n}" >&2
fi
first=0
for (( idx = 0; idx < n; idx++ )); do
name="$(basename -- "${SSH_SOCKET_DIRS[$idx]}")"
if [[ -n "${ticked["${name}"]:-}" ]]; then box='x'; else box=' '; fi
if (( idx == i )); then
printf '\033[7m> [%s] %s (%s)\033[0m\n' \
"${box}" "${SSH_SOCKET_LABELS[$idx]}" "${SSH_SOCKET_STATES[$idx]}" >&2
else
printf ' [%s] %s (%s)\n' \
"${box}" "${SSH_SOCKET_LABELS[$idx]}" "${SSH_SOCKET_STATES[$idx]}" >&2
fi
done
}
printf 'Select SSH hosts to expose to the container (space toggles, Enter accepts):\n' >&2
redraw_ssh_picker
while true; do
if (( interrupted )); then i=-1; break; fi
# Timed read: lets us notice Ctrl-C (via the flag) and a lone Esc key.
if ! IFS= read -rsn1 -t 0.3 key; then
(( interrupted )) && { i=-1; break; }
continue
fi
case "${key}" in
$'\x1b') # escape: arrow-key prefix
IFS= read -rsn1 -t 0.3 rest || rest=''
case "${rest}" in
'[') IFS= read -rsn1 -t 0.3 key || key='' ;;
*) key="${rest}" ;;
esac
case "${key}" in
A) i=$(( (i + n - 1) % n )); redraw_ssh_picker ;; # Up
B) i=$(( (i + 1) % n )); redraw_ssh_picker ;; # Down
esac
;;
'') break ;; # Enter: accept
$'\x03'|q|Q) i=-1; break ;; # Ctrl-C byte / q: cancel
' ')
name="$(basename -- "${SSH_SOCKET_DIRS[$i]}")"
if [[ -n "${ticked["${name}"]:-}" ]]; then
unset "ticked[${name}]"
else
ticked["${name}"]=1
fi
redraw_ssh_picker
;;
a|A)
if (( ${#ticked[@]} == n )); then
ticked=()
else
ticked=()
for (( idx = 0; idx < n; idx++ )); do
name="$(basename -- "${SSH_SOCKET_DIRS[$idx]}")"
ticked["${name}"]=1
done
fi
redraw_ssh_picker
;;
k) i=$(( (i + n - 1) % n )); redraw_ssh_picker ;;
j) i=$(( (i + 1) % n )); redraw_ssh_picker ;;
esac
done
trap - EXIT TERM INT
restore_tty
(( i < 0 )) && return 1
for (( idx = 0; idx < n; idx++ )); do
name="$(basename -- "${SSH_SOCKET_DIRS[$idx]}")"
[[ -n "${ticked["${name}"]:-}" ]] && PICK_SSH_DIRS+=("${name}")
done
return 0
}
# Resolve which SSH socket dirs to mount:
# - none: mount none
# - pick: always show the picker (keep the saved set if cancelled)
# - else: reuse the saved set after a Y/n prompt; n opens the picker.
# On first use the picker is shown directly; non-interactive runs
# mount none.
apply_ssh_socket_selection() {
SSH_MOUNT_DIRS=()
[[ "${SSH_SOCKETS_MODE}" == "none" ]] && return
discover_ssh_socket_dirs || return 0
ensure_ssh_socket_dirs
local -A index_by_name=()
local -A selected=()
local i name have_memory=0
local -a saved=() saved_names=() saved_dirs=() saved_labels=()
for (( i = 0; i < ${#SSH_SOCKET_DIRS[@]}; i++ )); do
index_by_name["$(basename -- "${SSH_SOCKET_DIRS[$i]}")"]="${i}"
done
if get_mem_ssh_dirs "${PROJECT_DIR}"; then
have_memory=1
saved=("${MEM_SSH_DIRS[@]}")
fi
# Map remembered names to the currently configured dirs.
for name in "${saved[@]}"; do
[[ -n "${index_by_name["${name}"]:-}" ]] || continue
i="${index_by_name["${name}"]}"
saved_names+=("${name}")
saved_dirs+=("${SSH_SOCKET_DIRS[$i]}")
saved_labels+=("${SSH_SOCKET_LABELS[$i]}")
done
if [[ "${SSH_SOCKETS_MODE}" == "pick" ]]; then
if pick_ssh_socket_dirs "${saved_names[@]}"; then
for name in "${PICK_SSH_DIRS[@]}"; do selected["${name}"]=1; done
save_mem_ssh_dirs "${PROJECT_DIR}" "${PICK_SSH_DIRS[@]}"
else
for name in "${saved_names[@]}"; do selected["${name}"]=1; done
(( ${#saved_names[@]} > 0 )) && echo "→ Keeping previous SSH host selection" >&2
fi
elif (( have_memory )); then
if (( ${#saved_names[@]} < ${#saved[@]} )); then
echo "→ Dropping SSH socket dirs no longer in ~/.ssh/config" >&2
fi
echo "SSH sockets for this project:"
if (( ${#saved_labels[@]} > 0 )); then
printf ' %s\n' "${saved_labels[@]}"
else
printf ' (none)\n'
fi
if prompt_yn "reuse ssh sockets [Y/n]" y; then
for name in "${saved_names[@]}"; do selected["${name}"]=1; done
if (( ${#saved_names[@]} < ${#saved[@]} )); then
save_mem_ssh_dirs "${PROJECT_DIR}" "${saved_names[@]}"
fi
else
if pick_ssh_socket_dirs "${saved_names[@]}"; then
for name in "${PICK_SSH_DIRS[@]}"; do selected["${name}"]=1; done
save_mem_ssh_dirs "${PROJECT_DIR}" "${PICK_SSH_DIRS[@]}"
else
for name in "${saved_names[@]}"; do selected["${name}"]=1; done
echo "→ Selection unchanged" >&2
fi
fi
else
# First run for this project.
if pick_ssh_socket_dirs; then
for name in "${PICK_SSH_DIRS[@]}"; do selected["${name}"]=1; done
save_mem_ssh_dirs "${PROJECT_DIR}" "${PICK_SSH_DIRS[@]}"
else
return 0
fi
fi
for (( i = 0; i < ${#SSH_SOCKET_DIRS[@]}; i++ )); do
name="$(basename -- "${SSH_SOCKET_DIRS[$i]}")"
[[ -n "${selected["${name}"]:-}" ]] && SSH_MOUNT_DIRS+=("${SSH_SOCKET_DIRS[$i]}")
done
return 0
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi