-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdeva.sh
More file actions
executable file
·2776 lines (2454 loc) · 86.5 KB
/
deva.sh
File metadata and controls
executable file
·2776 lines (2454 loc) · 86.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
AGENTS_DIR="$SCRIPT_DIR/agents"
DEVA_DOCKER_IMAGE_ENV_SET=false
if [ -n "${DEVA_DOCKER_IMAGE+x}" ]; then
DEVA_DOCKER_IMAGE_ENV_SET=true
fi
DEVA_DOCKER_TAG_ENV_SET=false
if [ -n "${DEVA_DOCKER_TAG+x}" ]; then
DEVA_DOCKER_TAG_ENV_SET=true
fi
VERSION="0.10.0"
DEVA_DOCKER_IMAGE="${DEVA_DOCKER_IMAGE:-ghcr.io/thevibeworks/deva}"
DEVA_DOCKER_TAG="${DEVA_DOCKER_TAG:-latest}"
DEVA_CONTAINER_PREFIX="${DEVA_CONTAINER_PREFIX:-deva}"
DEFAULT_AGENT="${DEVA_DEFAULT_AGENT:-claude}"
PROFILE="${DEVA_PROFILE:-${DEVA_IMAGE_PROFILE:-}}"
CONFIG_ROOT=""
USER_VOLUMES=()
USER_ENVS=()
EXTRA_DOCKER_ARGS=()
DOCKER_TERMINAL_ARGS=()
CONFIG_HOME=""
CONFIG_HOME_AUTO=false
CONFIG_HOME_FROM_CLI=false
AUTOLINK=true
_WS_HASH_CACHE=""
if [ -n "${DEVA_NO_AUTOLINK:-}" ]; then AUTOLINK=false; fi
SKIP_CONFIG=false
CONFIG_ERRORS=()
LOADED_CONFIGS=()
AGENT_ARGS=()
AGENT_EXPLICIT=false
normalize_docker_image_parts() {
local tail="${DEVA_DOCKER_IMAGE##*/}"
if [[ "$DEVA_DOCKER_IMAGE" == *@* ]]; then
DEVA_DOCKER_TAG=""
DEVA_DOCKER_TAG_ENV_SET=true
return
fi
if [[ "$tail" == *:* ]]; then
local embedded_tag="${tail##*:}"
DEVA_DOCKER_IMAGE="${DEVA_DOCKER_IMAGE%:*}"
if [ "$DEVA_DOCKER_TAG_ENV_SET" = false ]; then
DEVA_DOCKER_TAG="$embedded_tag"
DEVA_DOCKER_TAG_ENV_SET=true
fi
fi
}
docker_image_ref() {
if [[ "$DEVA_DOCKER_IMAGE" == *@* ]]; then
printf '%s' "$DEVA_DOCKER_IMAGE"
elif [ -n "${DEVA_DOCKER_TAG:-}" ]; then
printf '%s:%s' "$DEVA_DOCKER_IMAGE" "$DEVA_DOCKER_TAG"
else
printf '%s' "$DEVA_DOCKER_IMAGE"
fi
}
normalize_docker_image_parts
EPHEMERAL_MODE=false
QUICK_MODE=false
GLOBAL_MODE=false
DEBUG_MODE=false
DRY_RUN=false
if [ -t 0 ] && [ -t 1 ]; then
DOCKER_TERMINAL_ARGS=(-it)
elif [ ! -t 0 ]; then
DOCKER_TERMINAL_ARGS=(-i)
fi
usage() {
cat <<'USAGE'
deva.sh - Docker-based multi-agent launcher (Claude, Codex, Gemini)
Usage:
deva.sh [deva flags] [agent] [-- agent-flags]
deva.sh [agent] [deva flags] [-- agent-flags]
deva.sh <command>
Container management commands (docker/tmux-style):
deva.sh ps [-g] List containers (current project or --all)
deva.sh status [-g] Show session info (current workspace or --all)
deva.sh shell [-g] Open zsh shell for inspection (pick if multiple)
deva.sh stop [-g] Stop container (pick if multiple)
deva.sh rm [-g] [--all] Remove container (pick if multiple), or all for this workspace
deva.sh clean [-g] Remove all stopped containers
Advanced:
deva.sh --show-config Show resolved configuration (debug)
Deva flags:
--rm Ephemeral mode: remove container after exit
-g, --global Global mode: access containers from all projects
-v SRC:DEST[:OPT] Mount additional volumes inside the container
-c DIR, --config-home DIR
Mount an alternate auth/config home into /home/deva
-e VAR[=VALUE] Pass environment variable into the container (pulls from host when VALUE omitted)
-p NAME, --profile NAME
Select profile: base (default), rust. Pulls tag, falls back to Dockerfile.<profile>
-Q, --quick Bare mode: no host config mounts, no .deva loading, no autolink,
implies --rm. Like emacs -Q. Mutually exclusive with -c.
--host-net Use host networking for the agent container
--no-docker Disable auto-mount of Docker socket (default: auto-mount if present)
--dry-run Show docker command without executing the container (implies --debug)
--verbose, --debug Print full docker command before execution
-- Everything after this sentinel is passed to the agent unchanged
Chrome integration for `claude -- --chrome`:
Set one of these in `.deva.local` or pass with `-e`:
DEVA_CHROME_PROFILE_PATH=/path/to/Profile 6
Mount that profile's `Extensions/` tree for detection
DEVA_CHROME_PROFILE_NAME=Profile 6
Override target profile name when source basename differs
DEVA_CHROME_USER_DATA_DIR=/path/to/Chrome user data
Scan `Default`/`Profile *` and mount only `Extensions/`
DEVA_HOST_CHROME_BRIDGE_DIR=/path/to/claude-mcp-browser-bridge-$USER
Override the exact host bridge directory if needed
Container Behavior (NEW in v0.8.0):
Default (persistent): Shared per project by default, but split when container shape changes
(image/profile, extra volumes, explicit config-home, auth mode).
Preserves state (npm packages, builds, etc).
Faster startup, and default-auth runs can share one warm container.
With --rm (ephemeral): Create new container, auto-remove after exit.
Agent-specific naming for parallel runs.
Container Naming (NEW):
Persistent: deva-<parent>-<project>[..shape] # shape may encode image/volumes/config/auth
Ephemeral: deva-<parent>-<project>-<agent>-<pid> # Agent-specific
Example:
/Users/eric/work/myapp → deva-work-myapp
/Users/eric/home/myapp → deva-home-myapp
Examples:
# Launch agents (persistent by default)
deva.sh # Launch claude in persistent container
deva.sh claude # Same
deva.sh codex # Launch codex in the same default container shape
deva.sh gemini # Launch gemini in the same default container shape
deva.sh claude --rm # Ephemeral: deva-work-myapp-claude-12345
# Container management (current project)
deva.sh ps # List containers for this project
deva.sh shell # Open zsh for inspection
deva.sh stop # Stop container
deva.sh rm # Remove container
deva.sh clean # Clean stopped containers
# Global mode (all projects)
deva.sh ps -g # List ALL deva containers
deva.sh shell -g # Open shell in any container
deva.sh stop -g # Stop any container
Advanced:
deva.sh codex -v ~/.ssh:/home/deva/.ssh:ro -- -m gpt-5-codex
deva.sh claude -- --trace --continue # Use claude-trace wrapper for request tracing
deva.sh --show-config # Debug configuration
deva.sh --no-docker claude # Disable Docker-in-Docker auto-mount
USAGE
}
expand_tilde() {
local path="$1"
if [[ "$path" == ~* ]]; then
path="${path/#~/$HOME}"
fi
printf '%s' "$path"
}
absolute_path() {
python3 - "$1" <<'PY'
import os, sys
print(os.path.abspath(sys.argv[1]))
PY
}
canonical_path() {
python3 - "$1" <<'PY'
import os, sys
print(os.path.realpath(sys.argv[1]))
PY
}
default_config_home_for_agent() {
local agent="$1"
local xdg_home
xdg_home="${XDG_CONFIG_HOME:-$HOME/.config}"
printf '%s' "$xdg_home/deva/$agent"
}
validate_profile() {
case "$1" in
base | rust | "") return 0 ;;
*) return 1 ;;
esac
}
set_config_home_value() {
local raw="$1"
raw="$(expand_tilde "$raw")"
CONFIG_HOME="$(absolute_path "$raw")"
}
check_agent() {
local agent="$1"
if [ ! -f "$AGENTS_DIR/$agent.sh" ]; then
local available=""
local file
for file in "$AGENTS_DIR"/*.sh; do
[ -e "$file" ] || continue
available+="$(basename "$file" .sh) "
done
available="${available%% }"
echo "error: unknown agent '$agent'" >&2
echo "available agents: ${available}" >&2
exit 1
fi
}
check_image() {
local image_ref
image_ref="$(docker_image_ref)"
if docker image inspect "$image_ref" >/dev/null 2>&1; then
return
fi
# Try pulling first
if docker pull "$image_ref" >/dev/null 2>&1; then
return
fi
# Smart fallback: check for available profile images locally.
# Digest-pinned refs are exact; tag fallback does not make sense there.
local available_tags=""
if [[ "$DEVA_DOCKER_IMAGE" != *@* ]]; then
# Check common profile tags (prefer rust as it's a superset of base)
for tag in rust latest; do
if [ "$tag" = "$DEVA_DOCKER_TAG" ]; then
continue # Skip the one we already tried
fi
if docker image inspect "${DEVA_DOCKER_IMAGE}:${tag}" >/dev/null 2>&1; then
available_tags="${available_tags}${tag} "
fi
done
fi
if [ -n "$available_tags" ]; then
# Found alternative images - use the first one
local fallback_tag="${available_tags%% *}" # Get first tag
echo "Image $image_ref not found" >&2
echo "Using available image: ${DEVA_DOCKER_IMAGE}:${fallback_tag}" >&2
DEVA_DOCKER_TAG="$fallback_tag"
return
fi
# Determine matching local Dockerfile for suggestions (no auto-build)
local df=""
case "${PROFILE:-}" in
rust)
[ -f "${SCRIPT_DIR}/Dockerfile.rust" ] && df="${SCRIPT_DIR}/Dockerfile.rust" || df=""
;;
esac
echo "Docker image $image_ref not found locally" >&2
if [ -n "$df" ]; then
echo "A matching Dockerfile exists at: $df" >&2
case "${PROFILE:-}" in
rust)
echo "Build with: make build-rust" >&2
echo "Manual docker builds need explicit build args and BASE_IMAGE; see docs/custom-images.md" >&2
;;
"" | base)
echo "Build with: make build" >&2
echo "Manual docker builds need explicit build args; see docs/custom-images.md" >&2
;;
*)
echo "Build with your Dockerfile and tag appropriately (e.g., :${PROFILE})" >&2
;;
esac
else
echo "Pull with: docker pull $image_ref" >&2
fi
exit 1
}
dangerous_directory() {
local dir
dir="$(pwd)"
local bad_dirs=("$HOME" "/" "/etc" "/usr" "/var" "/bin" "/sbin" "/lib" "/lib64" "/boot" "/dev" "/proc" "/sys" "/tmp" "/root" "/mnt" "/media" "/srv")
for item in "${bad_dirs[@]}"; do
if [ "$dir" = "$item" ]; then
return 0
fi
done
if [ "$dir" = "$(dirname "$HOME")" ]; then
return 0
fi
return 1
}
warn_dangerous_directory() {
local current_dir
current_dir="$(pwd)"
cat <<EOF
WARNING: Running in a high-risk directory!
Current directory: ${current_dir}
deva.sh will grant full access to this directory and all subdirectories.
Type 'yes' to continue:
EOF
read -r response
if [ "$response" != "yes" ]; then
echo "Aborted. Change to a specific project directory."
exit 1
fi
}
translate_localhost() {
echo "$1" | sed 's/127\.0\.0\.1/host.docker.internal/g' | sed 's/localhost/host.docker.internal/g'
}
claude_args_request_chrome() {
local arg
local wants_chrome=false
local disables_chrome=false
for arg in "$@"; do
case "$arg" in
--chrome)
wants_chrome=true
;;
--no-chrome)
disables_chrome=true
;;
esac
done
[ "$wants_chrome" = true ] && [ "$disables_chrome" = false ]
}
get_host_tmpdir() {
local tmpdir=""
if command -v node >/dev/null 2>&1; then
tmpdir=$(node -p 'require("os").tmpdir()' 2>/dev/null || true)
fi
if [ -z "$tmpdir" ] && command -v python3 >/dev/null 2>&1; then
tmpdir=$(python3 - <<'PY'
import tempfile
print(tempfile.gettempdir())
PY
)
fi
if [ -z "$tmpdir" ]; then
tmpdir="${TMPDIR:-/tmp}"
fi
printf '%s' "$tmpdir"
}
normalize_host_bind_path() {
local path="$1"
path="$(expand_tilde "$path")"
if [[ "$path" == /* ]]; then
printf '%s' "$path"
return 0
fi
absolute_path "$path"
}
configured_env_value() {
local name="$1"
local spec
for spec in "${USER_ENVS[@]+"${USER_ENVS[@]}"}"; do
if [[ "$spec" == "$name="* ]]; then
printf '%s' "${spec#*=}"
return 0
fi
if [ "$spec" = "$name" ] && [ -n "${!name-}" ]; then
printf '%s' "${!name}"
return 0
fi
done
if [ -n "${!name-}" ]; then
printf '%s' "${!name}"
return 0
fi
return 1
}
user_volume_mounts_target() {
local target="$1"
local spec remainder dest
for spec in "${USER_VOLUMES[@]+"${USER_VOLUMES[@]}"}"; do
remainder="${spec#*:}"
dest="${remainder%%:*}"
if [ "$dest" = "$target" ]; then
return 0
fi
done
return 1
}
prepare_claude_chrome_detection_mount() {
local profile_path=""
local user_data_dir=""
local profile_name=""
local profile_target=""
local extensions_source=""
local found_profile=false
profile_path="$(configured_env_value DEVA_CHROME_PROFILE_PATH || true)"
user_data_dir="$(configured_env_value DEVA_CHROME_USER_DATA_DIR || true)"
if [ -n "$profile_path" ]; then
profile_path="$(normalize_host_bind_path "$profile_path")"
if [ ! -d "$profile_path" ]; then
echo "error: DEVA_CHROME_PROFILE_PATH does not exist: $profile_path" >&2
exit 1
fi
profile_name="$(configured_env_value DEVA_CHROME_PROFILE_NAME || true)"
if [ -z "$profile_name" ]; then
profile_name="$(basename "$profile_path")"
fi
case "$profile_name" in
Default | "Profile "*)
;;
*)
echo "error: Chrome profile name must be 'Default' or 'Profile N'; got: $profile_name" >&2
echo "hint: set DEVA_CHROME_PROFILE_NAME='Profile 6' if the source path basename is different" >&2
exit 1
;;
esac
extensions_source="$profile_path/Extensions"
if [ ! -d "$extensions_source" ]; then
echo "error: Chrome profile is missing Extensions directory: $extensions_source" >&2
exit 1
fi
profile_target="/home/deva/.config/google-chrome/$profile_name/Extensions"
if ! user_volume_mounts_target "$profile_target"; then
USER_VOLUMES+=("$extensions_source:$profile_target:ro")
fi
return 0
fi
if [ -n "$user_data_dir" ]; then
user_data_dir="$(normalize_host_bind_path "$user_data_dir")"
if [ ! -d "$user_data_dir" ]; then
echo "error: DEVA_CHROME_USER_DATA_DIR does not exist: $user_data_dir" >&2
exit 1
fi
if [ -d "$user_data_dir/Default" ]; then
extensions_source="$user_data_dir/Default/Extensions"
if [ -d "$extensions_source" ]; then
profile_target="/home/deva/.config/google-chrome/Default/Extensions"
if ! user_volume_mounts_target "$profile_target"; then
USER_VOLUMES+=("$extensions_source:$profile_target:ro")
fi
found_profile=true
fi
fi
local candidate
for candidate in "$user_data_dir"/Profile\ *; do
[ -d "$candidate" ] || continue
extensions_source="$candidate/Extensions"
[ -d "$extensions_source" ] || continue
profile_name="$(basename "$candidate")"
profile_target="/home/deva/.config/google-chrome/$profile_name/Extensions"
if ! user_volume_mounts_target "$profile_target"; then
USER_VOLUMES+=("$extensions_source:$profile_target:ro")
fi
found_profile=true
done
if [ "$found_profile" = false ]; then
echo "error: DEVA_CHROME_USER_DATA_DIR has no Default/Profile */Extensions directories: $user_data_dir" >&2
exit 1
fi
fi
}
resolve_claude_chrome_bridge_dir() {
local host_user="$1"
local configured_bridge_dir=""
local host_tmpdir=""
local host_bridge_dir=""
configured_bridge_dir="$(configured_env_value DEVA_HOST_CHROME_BRIDGE_DIR || true)"
if [ -n "$configured_bridge_dir" ]; then
host_bridge_dir="$(normalize_host_bind_path "$configured_bridge_dir")"
else
host_tmpdir="$(get_host_tmpdir)"
local tmp_bridge_dir="$host_tmpdir/claude-mcp-browser-bridge-$host_user"
# Claude's native host currently creates the bridge under /tmp, while the
# client also probes os.tmpdir() as an extra lookup path. Keep /tmp as
# the default mount target and only prefer os.tmpdir() when it already
# exists and /tmp does not.
host_bridge_dir="/tmp/claude-mcp-browser-bridge-$host_user"
if [ ! -d "$host_bridge_dir" ] && [ "$host_tmpdir" != "/tmp" ] && [ -d "$tmp_bridge_dir" ]; then
host_bridge_dir="$tmp_bridge_dir"
fi
fi
mkdir -p "$host_bridge_dir"
chmod 700 "$host_bridge_dir" 2>/dev/null || true
canonical_path "$host_bridge_dir"
}
prepare_claude_chrome_bridge() {
[ "$ACTIVE_AGENT" = "claude" ] || return 0
if ! claude_args_request_chrome "${AGENT_ARGV[@]+"${AGENT_ARGV[@]}"}"; then
return 0
fi
local host_user
host_user="$(configured_env_value DEVA_CHROME_HOST_USER || true)"
if [ -z "$host_user" ]; then
host_user="$(id -un)"
fi
local host_bridge_dir
host_bridge_dir="$(resolve_claude_chrome_bridge_dir "$host_user")"
prepare_claude_chrome_detection_mount
local bridge_mount="/deva-host-chrome-bridge"
if ! user_volume_mounts_target "$bridge_mount"; then
USER_VOLUMES+=("$host_bridge_dir:$bridge_mount")
fi
USER_ENVS+=("DEVA_CHROME_HOST_BRIDGE=1")
USER_ENVS+=("DEVA_CHROME_HOST_USER=$host_user")
USER_ENVS+=("DEVA_CHROME_HOST_BRIDGE_DIR=$bridge_mount")
}
append_unique_line() {
local list="$1"
local item="$2"
if [ -z "$item" ]; then
printf '%s' "$list"
return
fi
if [ -n "$list" ] && printf '%s\n' "$list" | grep -F -x -q -- "$item"; then
printf '%s' "$list"
return
fi
if [ -n "$list" ]; then
printf '%s\n%s' "$list" "$item"
else
printf '%s' "$item"
fi
}
sanitize_slug_component() {
printf '%s' "$1" | sed 's/[^a-zA-Z0-9]/-/g' | sed 's/--*/-/g' | sed 's/^-//' | sed 's/-$//'
}
compute_slug_components_for_path() {
local path="$1"
local dir_path
if [ -d "$path" ]; then
dir_path="$(cd "$path" 2>/dev/null && pwd)"
else
dir_path="$(cd "$(dirname "$path")" 2>/dev/null && pwd)"
fi
[ -n "$dir_path" ] || dir_path="$(pwd)"
local project parent
project="$(basename "$dir_path")"
parent="$(basename "$(dirname "$dir_path")")"
case "$parent" in
src | github.com | gitlab.com | bitbucket.org | repos | projects | work | code | dev)
parent="$(basename "$(dirname "$(dirname "$dir_path")")")"
;;
esac
local sanitized_parent sanitized_project
sanitized_parent="$(sanitize_slug_component "$parent")"
sanitized_project="$(sanitize_slug_component "$project")"
printf '%s %s\n' "$sanitized_parent" "$sanitized_project"
}
generate_container_slug_for_path() {
local path="$1"
local parent project
read -r parent project <<<"$(compute_slug_components_for_path "$path")"
if [ -z "$project" ]; then
echo "$parent"
return
fi
if [ -n "$parent" ] && [[ "$project" == *"$parent"* ]] && [ ${#parent} -gt 3 ]; then
echo "$project"
elif [ -n "$parent" ]; then
echo "${parent}-${project}"
else
echo "$project"
fi
}
generate_container_slug() {
generate_container_slug_for_path "$(pwd)"
}
slug_candidates_for_path() {
local path="$1"
local parent project
read -r parent project <<<"$(compute_slug_components_for_path "$path")"
local variants=""
if [ -n "$project" ]; then
variants="$(append_unique_line "$variants" "$project")"
local trimmed="$project"
while [ -n "$trimmed" ]; do
if [[ "$trimmed" =~ -[0-9]+$ ]]; then
trimmed="${trimmed%-*}"
if [ -n "$trimmed" ]; then
variants="$(append_unique_line "$variants" "$trimmed")"
continue
fi
continue
fi
if [[ "$trimmed" =~ -(copilot|yolo|yolo-mode|share)$ ]]; then
trimmed="${trimmed%-*}"
if [ -n "$trimmed" ]; then
variants="$(append_unique_line "$variants" "$trimmed")"
continue
fi
continue
fi
break
done
fi
local slugs="$variants"
if [ -n "$parent" ]; then
local variant combined
for variant in $variants; do
[ -n "$variant" ] || continue
if [ ${#parent} -gt 3 ] && [[ "$variant" == *"$parent"* ]]; then
combined="$variant"
else
combined="${parent}-${variant}"
fi
slugs="$(append_unique_line "$slugs" "$combined")"
done
slugs="$(append_unique_line "$slugs" "$parent")"
fi
printf '%s\n' "$slugs" | sed '/^$/d'
}
project_container_rows() {
local rows
if [ "$GLOBAL_MODE" = true ]; then
rows=$(docker ps --filter "name=${DEVA_CONTAINER_PREFIX}-" --format '{{.Names}}\t{{.Status}}\t{{.CreatedAt}}')
[ -n "$rows" ] && printf "%s\n" "$rows"
return
fi
# Prefer workspace label match when available (new containers)
local ws_hash
ws_hash=$(workspace_hash)
rows=$(docker ps --filter "label=deva.workspace_hash=$ws_hash" --format '{{.Names}}\t{{.Status}}\t{{.CreatedAt}}')
if [ -n "$rows" ]; then
printf "%s\n" "$rows"
return
fi
# Fallback to slug-based name filtering for legacy containers
rows=$(docker ps --filter "name=${DEVA_CONTAINER_PREFIX}-" --format '{{.Names}}\t{{.Status}}\t{{.CreatedAt}}')
if [ -z "$rows" ]; then
return
fi
# Continue to slug filtering below (don't return here!)
local path="$PWD"
local slugs=""
while true; do
local slug
for slug in $(slug_candidates_for_path "$path"); do
[ -n "$slug" ] || continue
slugs="$(append_unique_line "$slugs" "$slug")"
done
local parent_path
parent_path="$(dirname "$path")"
if [ "$parent_path" = "$path" ] || [ -z "$parent_path" ]; then
break
fi
path="$parent_path"
done
if [ -z "$slugs" ]; then
printf "%s\n" "$rows"
return
fi
local pattern=""
local slug escaped
for slug in $slugs; do
[ -n "$slug" ] || continue
escaped=$(printf '%s' "$slug" | sed -e 's/[.[\\^$*+?{}()|]/\\&/g')
if [ -n "$pattern" ]; then
pattern="${pattern}|-${escaped}([.-]|$)"
else
pattern="-${escaped}([.-]|$)"
fi
done
if [ -z "$pattern" ]; then
printf "%s\n" "$rows"
return
fi
local filtered
filtered=$(printf "%s\n" "$rows" | grep -E -- "$pattern" || true)
if [ -n "$filtered" ]; then
printf "%s\n" "$filtered"
else
printf "%s\n" "$rows"
fi
}
extract_agent_from_name() {
local name="$1"
local rest="${name#"${DEVA_CONTAINER_PREFIX}"-}"
# Ephemeral pattern: ends with -<agent>-<pid> where pid is all digits
if [[ "$rest" =~ -([a-z]+)-([0-9]+)$ ]]; then
local agent="${BASH_REMATCH[1]}"
printf '%s' "$agent"
else
printf 'share'
fi
}
pick_container() {
local rows
rows=$(project_container_rows)
if [ -z "$rows" ]; then
echo "No running containers found for project $(basename "$(pwd)")" >&2
return 1
fi
local count
count=$(printf '%s\n' "$rows" | wc -l | tr -d ' ')
if [ "$count" -eq 1 ]; then
printf '%s\n' "${rows%%$'\t'*}"
return 0
fi
local formatted
formatted=$(printf '%s\n' "$rows" | while IFS=$'\t' read -r name status created; do
printf '%s\t%s\t%s\t%s\n' "$name" "$(extract_agent_from_name "$name")" "$status" "$created"
done)
if command -v fzf >/dev/null 2>&1; then
local selection
selection=$(printf '%s\n' "$formatted" | fzf --with-nth=1,2,4 --prompt="Select container> " --height=15 --border)
[ -n "$selection" ] || return 1
printf '%s\n' "${selection%%$'\t'*}"
return 0
fi
local idx=1
printf 'Running containers:\n'
printf '%s\n' "$formatted" | while IFS=$'\t' read -r name agent status created; do
printf ' %d) %s\t[%s]\t%s\t%s\n' "$idx" "$name" "$agent" "$status" "$created"
idx=$((idx + 1))
done
printf 'Select container (1-%d): ' "$((idx - 1))"
read -r choice
if [[ "$choice" =~ ^[0-9]+$ ]] && [ "$choice" -ge 1 ] && [ "$choice" -lt "$idx" ]; then
local selected
selected=$(printf '%s\n' "$formatted" | sed -n "${choice}p")
printf '%s\n' "${selected%%$'\t'*}"
return 0
fi
return 1
}
list_containers_pretty() {
local rows
rows=$(project_container_rows)
if [ -z "$rows" ]; then
echo "No running containers found for project $(basename "$(pwd)")"
return
fi
local output
output=$(
{
printf 'NAME\tAGENT\tSTATUS\tCREATED AT\n'
printf '%s\n' "$rows" | while IFS=$'\t' read -r name status created; do
printf '%s\t%s\t%s\t%s\n' "$name" "$(extract_agent_from_name "$name")" "$status" "$created"
done
}
)
if command -v column >/dev/null 2>&1; then
printf '%s\n' "$output" | column -t -s $'\t'
else
printf '%s\n' "$output"
fi
}
show_config() {
echo "=== deva.sh Configuration Debug ==="
echo ""
echo "Active Agent: ${ACTIVE_AGENT:-<not set>}"
echo "Default Agent: $DEFAULT_AGENT"
echo "Config Home: ${CONFIG_HOME:-<none>}"
echo "Config Home CLI: $CONFIG_HOME_FROM_CLI"
echo ""
if [ ${#LOADED_CONFIGS[@]} -gt 0 ]; then
echo "Loaded config files (in order):"
for cfg in "${LOADED_CONFIGS[@]}"; do
echo " - $cfg"
done
else
echo "No config files loaded"
fi
echo ""
if [ ${#USER_VOLUMES[@]} -gt 0 ]; then
echo "Volume mounts:"
for vol in "${USER_VOLUMES[@]}"; do
echo " -v $vol"
done
else
echo "No volume mounts"
fi
echo ""
if [ ${#USER_ENVS[@]} -gt 0 ]; then
echo "Environment variables:"
for env in "${USER_ENVS[@]}"; do
if [[ "$env" =~ (API_KEY|TOKEN|SECRET|PASSWORD)= ]]; then
echo " -e ${env%%=*}=<masked>"
else
echo " -e $env"
fi
done
else
echo "No environment variables"
fi
echo ""
echo "Docker image: $(docker_image_ref)"
echo "Container prefix: $DEVA_CONTAINER_PREFIX"
}
prepare_base_docker_args() {
local container_name
local slug
slug="$(generate_container_slug)"
local volume_hash=""
if [ ${#USER_VOLUMES[@]} -gt 0 ]; then
volume_hash=$(compute_volume_hash)
fi
# Include config-home in container identity when explicit.
# Use CONFIG_HOME if set, else CONFIG_ROOT (root mode clears CONFIG_HOME).
local config_hash=""
local config_hash_source=""
if [ "$CONFIG_HOME_FROM_CLI" = true ]; then
if [ -n "$CONFIG_HOME" ]; then
config_hash_source="$CONFIG_HOME"
elif [ -n "$CONFIG_ROOT" ]; then
config_hash_source="$CONFIG_ROOT"
fi
fi
[ -n "$config_hash_source" ] && config_hash=$(short_hash "$config_hash_source" 6)
local image_hash=""
image_hash=$(short_hash "$(docker_image_ref)" 6)
local suffix=""
[ -n "$image_hash" ] && suffix="..i${image_hash}"
[ -n "$volume_hash" ] && suffix="${suffix}..v${volume_hash}"
[ -n "$config_hash" ] && suffix="${suffix}..c${config_hash}"
if [ "$EPHEMERAL_MODE" = true ]; then
container_name="${DEVA_CONTAINER_PREFIX}-${slug}${suffix}-${ACTIVE_AGENT}-$$"
DOCKER_ARGS=(run --rm "${DOCKER_TERMINAL_ARGS[@]}")
else
container_name="${DEVA_CONTAINER_PREFIX}-${slug}${suffix}"
DOCKER_ARGS=(run -d)
fi
DOCKER_ARGS+=(
--name "$container_name"
-v "$(pwd):$(pwd)"
-w "$(pwd)"
-e "WORKDIR=$(pwd)"
-e "DEVA_AGENT=${ACTIVE_AGENT}"
-e "DEVA_UID=$(id -u)"
-e "DEVA_GID=$(id -g)"
--add-host host.docker.internal:host-gateway
)
# Attach labels to identify workspace and container grouping
local ws_hash
ws_hash=$(workspace_hash)
DOCKER_ARGS+=(
--label "deva.prefix=${DEVA_CONTAINER_PREFIX}"
--label "deva.slug=${slug}"
--label "deva.workspace=$(pwd)"
--label "deva.workspace_hash=${ws_hash}"
--label "deva.agent=${ACTIVE_AGENT}"
--label "deva.ephemeral=${EPHEMERAL_MODE}"
--label "deva.image=$(docker_image_ref)"
)
if [ -n "$volume_hash" ]; then
DOCKER_ARGS+=(--label "deva.volhash=${volume_hash}")
fi
if [ -n "$image_hash" ]; then
DOCKER_ARGS+=(--label "deva.image_hash=${image_hash}")
fi
if [ -n "${LANG:-}" ]; then DOCKER_ARGS+=(-e "LANG=$LANG"); fi
if [ -n "${LC_ALL:-}" ]; then DOCKER_ARGS+=(-e "LC_ALL=$LC_ALL"); fi
if [ -n "${TZ:-}" ]; then DOCKER_ARGS+=(-e "TZ=$TZ"); fi
# Auto-mount Docker socket for DinD workflows (opt-out via --no-docker or DEVA_NO_DOCKER=1)
if [ -z "${DEVA_NO_DOCKER:-}" ] && [ -S /var/run/docker.sock ]; then
DOCKER_ARGS+=(-v "/var/run/docker.sock:/var/run/docker.sock")
fi
# Fallback: detect host TZ/LANG if not set in env
if ! docker_args_has_env "TZ"; then
local host_tz=""
if command -v timedatectl >/dev/null 2>&1; then
host_tz=$(timedatectl show -p Timezone --value 2>/dev/null || true)
fi
if [ -z "$host_tz" ] && [ -L "/etc/localtime" ]; then
local tz_target
tz_target=$(readlink "/etc/localtime" 2>/dev/null || true)
case "$tz_target" in
*/zoneinfo/*)
host_tz="${tz_target##*/zoneinfo/}"
;;
esac
fi
if [ -z "$host_tz" ] && command -v systemsetup >/dev/null 2>&1; then
host_tz=$(systemsetup -gettimezone 2>/dev/null | awk -F': ' '{print $2}')
fi
if [ -n "$host_tz" ]; then DOCKER_ARGS+=(-e "TZ=$host_tz"); fi
fi
if ! docker_args_has_env "LANG"; then
local host_lang