Repository navigation
Expand file tree
/
Copy pathralph.sh
More file actions
executable file
·1832 lines (1592 loc) · 56.9 KB
/
Copy pathralph.sh
File metadata and controls
executable file
·1832 lines (1592 loc) · 56.9 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 -e
# ============================================================
# Ralph - Parallel AI Agent CLI
# Manages Docker containers for AI coding agents across any project
# ============================================================
VERSION="2.0.0"
BASE_IMAGE_NAME="ralph-base"
CONTAINER_PREFIX="ralph"
# Get the directory where this script is located (resolving symlinks)
SCRIPT_DIR="$(cd "$(dirname "$(realpath "${BASH_SOURCE[0]}")")" && pwd)"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# ============================================================
# Helper Functions
# ============================================================
log_info() {
echo -e "${BLUE}[INFO]${NC} $1"
}
log_success() {
echo -e "${GREEN}[OK]${NC} $1"
}
log_warn() {
echo -e "${YELLOW}[WARN]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# Find project root (look for .ralph/config.json)
find_ralph_config() {
local dir="$PWD"
while [ "$dir" != "/" ]; do
if [ -f "$dir/.ralph/config.json" ]; then
echo "$dir"
return 0
fi
dir="$(dirname "$dir")"
done
return 1
}
get_config_file() {
local root="$1"
if [ -f "$root/.ralph/config.json" ]; then
echo "$root/.ralph/config.json"
return 0
fi
return 1
}
# Get project name from config
get_project_name() {
local root="$1"
local config_file
config_file=$(get_config_file "$root") || { echo "project"; return; }
jq -r 'if (.repo|type) == "string" then ((.repo | split("/"))[-1] // "project") elif (.repo.name) then .repo.name else "project" end' "$config_file" | tr '[:upper:]' '[:lower:]'
}
# Get image name for project
get_image_name() {
local project_name="$1"
echo "ralph-${project_name}"
}
# Normalize task ID to container-safe format
normalize_task_id() {
echo "$1" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9-]/-/g'
}
# Parse task arguments: handles bare numbers, "issue 42", "--issue 42", etc.
# Sets: PARSED_TASK_ID (e.g., "issue-219")
# Args: all remaining arguments
parse_task_args() {
PARSED_TASK_ID=""
local task_type=""
local task_value=""
local collected_digits=""
local raw_id=""
while [[ $# -gt 0 ]]; do
case $1 in
--issue|--task|issue)
task_type="issue"
task_value="$2"
shift 2
;;
--prd|prd)
task_type="prd"
task_value="$2"
shift 2
;;
--prompt|prompt)
task_type="prompt"
task_value="$2"
shift 2
;;
-f|--follow|--all|-a)
# Skip flags handled by caller
shift
;;
*)
if [[ "$1" =~ ^[0-9]+$ ]]; then
collected_digits="${collected_digits}${1}"
elif [ -z "$raw_id" ]; then
raw_id="$1"
fi
shift
;;
esac
done
if [ -n "$task_type" ]; then
case "$task_type" in
issue) PARSED_TASK_ID="issue-$task_value" ;;
prd) PARSED_TASK_ID="prd-$(basename "$task_value")" ;;
prompt) PARSED_TASK_ID="$task_value" ;;
esac
elif [ -n "$collected_digits" ]; then
PARSED_TASK_ID="issue-$collected_digits"
elif [ -n "$raw_id" ]; then
PARSED_TASK_ID="$raw_id"
fi
}
# Get container name
container_name() {
local project_name="$1"
local task_id="$2"
echo "${CONTAINER_PREFIX}-${project_name}-$(normalize_task_id "$task_id")"
}
# Check if image exists
image_exists() {
docker image inspect "$1" &>/dev/null
}
# Check if container exists
container_exists() {
docker container inspect "$1" &>/dev/null 2>&1
}
# Check if container is running
container_running() {
[ "$(docker container inspect -f '{{.State.Running}}' "$1" 2>/dev/null)" = "true" ]
}
# ============================================================
# Commands
# ============================================================
show_usage() {
cat << EOF
Ralph - Parallel AI Agent CLI
Version: $VERSION
Usage: ralph.sh <command> [options]
Commands:
build-base Build the ralph-base Docker image
build Build project-specific image (run from project dir)
models List available opencode models
start Start a new agent container
restart Stop and restart a container with same task
attach Connect to agent for follow-up instructions
list List all Ralph containers
logs View container logs
tail Follow container logs (shorthand for logs -f)
stop Stop container(s)
status Show detailed status of a container
shell Open interactive shell in container
watch Watch containers and send macOS notifications on completion
notify [task] Send a test notification (or check status of a task)
clean Remove all stopped containers
init [--force] Initialize ralph config (interactive setup)
Start Options:
--issue <number> Work on a specific GitHub issue
--task <number> Alias for --issue
--prd <file> Use PRD mode with the given PRD file
--prompt <text> Use a custom prompt
--cli <name> Override agent CLI (opencode or claude)
--opencode Shorthand for --cli opencode
--claude Shorthand for --cli claude
--model <model> Override model (opencode only)
(no args) Let Ralph choose its own task based on config.json
Examples:
ralph.sh build-base # Build base image (one time)
ralph.sh build-base --node 24 # Build base image for Node 24
ralph.sh init # Interactive setup wizard
ralph.sh init --force # Re-run setup (overwrite config)
ralph.sh build # Build project image
ralph.sh start # Let Ralph choose a task
ralph.sh start 42 # Start agent on issue 42 (github mode)
ralph.sh start 2 1 9 # Start agent on issue 219 (digits joined)
ralph.sh start --issue 42 # Explicit issue flag
ralph.sh attach issue-42 # Connect for follow-up work
ralph.sh attach 42 # Connect using bare number
ralph.sh list # List all containers
ralph.sh tail 42 # Follow logs for issue 42
ralph.sh restart 42 # Stop and restart issue 42
ralph.sh stop --all # Stop all containers
Environment Variables:
GITHUB_TOKEN Required for GitHub operations
ANTHROPIC_API_KEY Required for opencode with Anthropic
RALPH_CPUS CPU limit per container (default: 2)
RALPH_MEMORY Memory limit per container (default: 4g)
EOF
}
cmd_build_base() {
local node_version=""
local image_tag="$BASE_IMAGE_NAME"
local build_args=()
while [[ $# -gt 0 ]]; do
case $1 in
--node|--node-version)
node_version="$2"
shift 2
;;
*)
log_error "Unknown option: $1"
exit 1
;;
esac
done
if [ -n "$node_version" ]; then
node_version="${node_version#v}"
image_tag="${BASE_IMAGE_NAME}-node${node_version}"
build_args+=(--build-arg "NODE_VERSION=$node_version")
log_info "Building ralph-base image (node $node_version)..."
else
log_info "Building ralph-base image..."
fi
docker build "${build_args[@]}" -t "$image_tag" -f "$SCRIPT_DIR/docker/Dockerfile.base" "$SCRIPT_DIR"
log_success "Base image built: $image_tag"
}
# Detect GitHub repo from git remote
detect_github_repo() {
git remote get-url origin 2>/dev/null | sed -E 's|.*github\.com[:/]||; s|\.git$||' || echo ""
}
detect_node_version() {
local root="$1"
local version=""
if [ -f "$root/.nvmrc" ]; then
version=$(tr -d 'v' < "$root/.nvmrc" | tr -d '[:space:]')
elif [ -f "$root/.node-version" ]; then
version=$(tr -d 'v' < "$root/.node-version" | tr -d '[:space:]')
fi
echo "$version"
}
detect_package_manager() {
local root="$1"
if [ -f "$root/pnpm-lock.yaml" ]; then
echo "pnpm"
return
fi
if [ -f "$root/yarn.lock" ]; then
echo "yarn"
return
fi
if [ -f "$root/package-lock.json" ] || [ -f "$root/npm-shrinkwrap.json" ]; then
echo "npm"
return
fi
echo ""
}
cmd_init() {
local target_dir="${1:-.}"
local force_setup=false
# Parse args
while [[ $# -gt 0 ]]; do
case $1 in
--force|-f) force_setup=true; shift ;;
*) target_dir="$1"; shift ;;
esac
done
# Check if config already exists
if [ -f "$target_dir/.ralph/config.json" ] && [ "$force_setup" = false ]; then
log_warn ".ralph/config.json already exists"
echo ""
read -p "Do you want to reconfigure? [y/N]: " reconfigure
if [[ ! "$reconfigure" =~ ^[Yy] ]]; then
echo "Use 'ralph init --force' to overwrite existing config"
return 0
fi
fi
echo ""
echo -e "${GREEN}Welcome to Ralph!${NC} Let's set up your project for parallel AI agents."
echo ""
# === Mode Selection ===
echo "Where should Ralph get tasks from?"
echo " 1) GitHub issues"
echo " 2) PRD file (prd.json)"
echo ""
read -p "Choose [1/2]: " task_choice
local mode="github"
local repo=""
local prd_file=""
case $task_choice in
1)
mode="github"
local detected=$(detect_github_repo)
if [ -n "$detected" ]; then
read -p "GitHub repo [$detected]: " repo
[ -z "$repo" ] && repo="$detected"
else
read -p "GitHub repo (owner/repo): " repo
fi
;;
2)
mode="prd"
read -p "Path to PRD file [./prd.json]: " prd_file
[ -z "$prd_file" ] && prd_file="./prd.json"
;;
*)
log_error "Invalid choice"
exit 1
;;
esac
# === Commit Mode ===
echo ""
echo "How should Ralph handle completed work?"
echo " 1) Raise a PR and wait for checks"
echo " 2) Commit to main and push"
echo " 3) Commit to main only (no push)"
echo " 4) Branch and commit (no push)"
echo " 5) Don't commit (leave files unstaged)"
echo ""
read -p "Choose [1/2/3/4/5]: " commit_choice
local commit_mode="pr"
case $commit_choice in
1|"") commit_mode="pr" ;;
2) commit_mode="main" ;;
3) commit_mode="commit" ;;
4) commit_mode="branch" ;;
5) commit_mode="none" ;;
*) log_error "Invalid choice"; exit 1 ;;
esac
# === Agent Review (only for PR mode) ===
local agent_review=""
if [ "$commit_mode" = "pr" ]; then
echo ""
echo "Should Ralph wait for an AI code reviewer?"
echo " 1) None (default)"
echo " 2) Copilot - Wait for GitHub Copilot review"
echo ""
read -p "Choose [1/2]: " review_choice
case $review_choice in
1|"") agent_review="" ;;
2) agent_review="copilot" ;;
*) log_error "Invalid choice"; exit 1 ;;
esac
fi
# === Agent Selection ===
echo ""
echo "Which AI agent should Ralph use?"
echo " 1) opencode (default)"
echo " 2) claude"
echo ""
read -p "Choose [1/2]: " agent_choice
local agent="opencode"
case $agent_choice in
1|"") agent="opencode" ;;
2) agent="claude" ;;
*) log_error "Invalid choice"; exit 1 ;;
esac
# === Notifications (optional) ===
echo ""
echo "Do you want to set up notifications? (optional)"
echo " 1) Skip for now"
echo " 2) ntfy.sh (free push notifications)"
echo " 3) Custom webhook"
echo ""
read -p "Choose [1/2/3]: " notify_choice
local ntfy_url=""
local webhook_url=""
case $notify_choice in
2)
read -p "ntfy.sh topic URL (e.g., https://ntfy.sh/my-ralph): " ntfy_url
;;
3)
read -p "Webhook URL: " webhook_url
;;
esac
# === Runtime (auto-detected) ===
local runtime_node
local runtime_pm
runtime_node=$(detect_node_version "$target_dir")
runtime_pm=$(detect_package_manager "$target_dir")
[ -z "$runtime_node" ] && runtime_node="24"
[ -z "$runtime_pm" ] && runtime_pm="pnpm"
# === Create directories ===
mkdir -p "$target_dir/ralph" "$target_dir/.ralph"
# === Build config.json ===
local config_file="$target_dir/.ralph/config.json"
cat > "$config_file" << EOF
{
"mode": "$mode",
"commitMode": "$commit_mode",
"repo": "$repo",
"prdFile": "$prd_file",
"runtime": {
"node": "$runtime_node",
"packageManager": "$runtime_pm"
},
"agent": "$agent",
"agentReview": "$agent_review",
"notifications": {
"webhook": "$webhook_url",
"ntfy": "$ntfy_url",
"onSuccess": true,
"onFailure": true
}
}
EOF
log_success "Created .ralph/config.json"
# === Copy Dockerfile if needed ===
if [ -f "$target_dir/ralph/Dockerfile" ]; then
log_warn "ralph/Dockerfile already exists, leaving it unchanged"
else
cp "$SCRIPT_DIR/templates/Dockerfile" "$target_dir/ralph/"
log_success "Created ralph/Dockerfile"
fi
# === Copy prompt.md if needed ===
if [ -f "$target_dir/ralph/prompt.md" ]; then
log_warn "ralph/prompt.md already exists, leaving it unchanged"
else
cp "$SCRIPT_DIR/templates/prompt.md" "$target_dir/ralph/"
log_success "Created ralph/prompt.md"
fi
# === Summary ===
echo ""
echo -e "${GREEN}Ralph is configured!${NC}"
echo ""
echo "Configuration:"
echo " Mode: $mode"
[ -n "$repo" ] && echo " Repo: $repo"
[ -n "$prd_file" ] && echo " PRD file: $prd_file"
echo " Commit mode: $commit_mode"
echo " Runtime: node $runtime_node, $runtime_pm"
echo " Agent: $agent"
[ -n "$agent_review" ] && echo " Review: $agent_review"
[ -n "$ntfy_url" ] && echo " Notify: $ntfy_url"
[ -n "$webhook_url" ] && echo " Webhook: $webhook_url"
echo ""
echo "Next steps:"
echo " 1. Review/edit .ralph/config.json if needed"
echo " 2. Customize ralph/prompt.md with project-specific instructions"
echo " 3. Run: ralph build"
echo " 4. Run: ralph start --issue <number>"
}
cmd_build() {
local project_root
if ! project_root=$(find_ralph_config); then
log_error "No config found (.ralph/config.json). Run 'ralph.sh init' first."
exit 1
fi
local config_file
if ! config_file=$(get_config_file "$project_root"); then
log_error "No config file found. Run 'ralph.sh init' first."
exit 1
fi
if [ ! -f "$project_root/ralph/Dockerfile" ]; then
log_error "No ralph/Dockerfile found. Run 'ralph.sh init' first."
exit 1
fi
local project_name=$(get_project_name "$project_root")
local image_name=$(get_image_name "$project_name")
local runtime_node
local runtime_pm
local install_cmd
local build_cmd
runtime_node=$(jq -r '.runtime.node // ""' "$config_file")
runtime_pm=$(jq -r '.runtime.packageManager // ""' "$config_file")
install_cmd=$(jq -r '.commands.install // ""' "$config_file")
build_cmd=$(jq -r '.commands.build // ""' "$config_file")
[ "$runtime_node" = "null" ] && runtime_node=""
[ "$runtime_pm" = "null" ] && runtime_pm=""
[ "$install_cmd" = "null" ] && install_cmd=""
[ "$build_cmd" = "null" ] && build_cmd=""
if [ -n "$runtime_node" ]; then
runtime_node="${runtime_node#v}"
fi
[ -z "$runtime_pm" ] && runtime_pm="pnpm"
local base_image="$BASE_IMAGE_NAME"
if [ -n "$runtime_node" ]; then
base_image="${BASE_IMAGE_NAME}-node${runtime_node}"
fi
log_info "Building image for project: $project_name"
# Check base image exists
if ! image_exists "$base_image"; then
log_warn "Base image not found: $base_image. Building it first..."
if [ -n "$runtime_node" ]; then
cmd_build_base --node "$runtime_node"
else
cmd_build_base
fi
fi
# Get GITHUB_TOKEN from gh auth if not set
if [ -z "$GITHUB_TOKEN" ]; then
if command -v gh &> /dev/null && gh auth status &> /dev/null; then
GITHUB_TOKEN=$(gh auth token 2>/dev/null)
if [ -n "$GITHUB_TOKEN" ]; then
log_info "Using token from gh auth"
export GITHUB_TOKEN
fi
fi
fi
# Build secrets from config (e.g., ["GITHUB_TOKEN", "TIPTAP_PRO_TOKEN"])
# These are passed securely via BuildKit --secret, not baked into image layers
local secret_args=""
local build_secrets=$(jq -r '.buildSecrets // [] | .[]' "$config_file" 2>/dev/null)
for secret_name in $build_secrets; do
# Convert to lowercase for the secret id (e.g., GITHUB_TOKEN -> github_token)
local secret_id=$(echo "$secret_name" | tr '[:upper:]' '[:lower:]')
# Check if the env var is set
local secret_value="${!secret_name}"
if [ -n "$secret_value" ]; then
secret_args="$secret_args --secret id=$secret_id,env=$secret_name"
else
log_warn "Secret $secret_name not set in environment"
fi
done
local build_args=(--build-arg "RALPH_BASE_IMAGE=$base_image" --build-arg "PACKAGE_MANAGER=$runtime_pm")
if [ -n "$install_cmd" ]; then
build_args+=(--build-arg "INSTALL_CMD=$install_cmd")
fi
if [ -n "$build_cmd" ]; then
build_args+=(--build-arg "BUILD_CMD=$build_cmd")
fi
local docker_build_args=()
if [ -n "$secret_args" ]; then
docker_build_args+=($secret_args)
fi
docker_build_args+=("${build_args[@]}")
DOCKER_BUILDKIT=1 docker build "${docker_build_args[@]}" -t "$image_name" "$project_root/ralph"
log_success "Image built: $image_name"
}
cmd_start() {
local project_root
if ! project_root=$(find_ralph_config); then
log_error "No config found (.ralph/config.json). Run 'ralph.sh init' first."
exit 1
fi
local config_file
if ! config_file=$(get_config_file "$project_root"); then
log_error "No config file found. Run 'ralph.sh init' first."
exit 1
fi
local project_name=$(get_project_name "$project_root")
local image_name=$(get_image_name "$project_name")
local task_type=""
local task_value=""
local task_id=""
local agent_cli_override=""
local model_override=""
local mode_from_config
mode_from_config=$(jq -r '.mode // "github"' "$config_file")
# Collect any bare numbers (for "ralph start 2 1 9" -> issue 219)
local collected_digits=""
# Parse arguments
while [[ $# -gt 0 ]]; do
case $1 in
--issue|--task)
task_type="issue"
task_value="$2"
task_id="issue-$2"
shift 2
;;
issue)
task_type="issue"
task_value="$2"
task_id="issue-$2"
shift 2
;;
--prd)
task_type="prd"
task_value="$2"
task_id="prd-$(basename "$2")"
shift 2
;;
prd)
task_type="prd"
task_value="$2"
task_id="prd-$(basename "$2")"
shift 2
;;
--prompt)
task_type="prompt"
task_value="$2"
task_id="custom-$(date +%s)"
shift 2
;;
--cli)
agent_cli_override="$2"
shift 2
;;
--opencode)
agent_cli_override="opencode"
shift
;;
--claude)
agent_cli_override="claude"
shift
;;
--model)
model_override="$2"
shift 2
;;
prompt)
task_type="prompt"
task_value="$2"
task_id="custom-$(date +%s)"
shift 2
;;
*)
# Check if it's a number (bare issue number in github mode)
if [[ "$1" =~ ^[0-9]+$ ]]; then
collected_digits="${collected_digits}${1}"
shift
else
log_error "Unknown option: $1"
show_usage
exit 1
fi
;;
esac
done
# If we collected digits and no explicit task type, treat as issue number in github mode
if [ -n "$collected_digits" ] && [ -z "$task_type" ]; then
if [ "$mode_from_config" = "github" ]; then
task_type="issue"
task_value="$collected_digits"
task_id="issue-$collected_digits"
else
log_error "Bare numbers only work in github mode. Use --prd or --prompt instead."
exit 1
fi
fi
if [ -z "$task_type" ]; then
task_id="auto-$(date +%s)"
fi
# Check prerequisites
if ! image_exists "$image_name"; then
log_error "Image not found: $image_name. Run 'ralph.sh build' first."
exit 1
fi
# Get GITHUB_TOKEN from gh auth if not set
if [ -z "$GITHUB_TOKEN" ]; then
if command -v gh &> /dev/null && gh auth status &> /dev/null; then
GITHUB_TOKEN=$(gh auth token 2>/dev/null)
if [ -n "$GITHUB_TOKEN" ]; then
log_info "Using token from gh auth"
fi
fi
fi
if [ "$task_type" = "issue" ] || { [ -z "$task_type" ] && [ "$mode_from_config" = "github" ]; }; then
if [ -z "$GITHUB_TOKEN" ]; then
log_error "GITHUB_TOKEN not set and gh auth not available"
log_info "Run 'gh auth login' or set GITHUB_TOKEN"
exit 1
fi
else
if [ -z "$GITHUB_TOKEN" ]; then
log_warn "GITHUB_TOKEN not set. GitHub operations may fail."
fi
fi
local cname=$(container_name "$project_name" "$task_id")
# Check if container already exists
if container_exists "$cname"; then
if container_running "$cname"; then
log_error "Container $cname is already running"
exit 1
else
log_warn "Removing stopped container $cname"
docker rm "$cname"
fi
fi
# Resource limits
local cpus="${RALPH_CPUS:-2}"
local memory="${RALPH_MEMORY:-4g}"
# Build docker run command
local docker_args=(
run
--detach
--name "$cname"
--cpus="$cpus"
--memory="$memory"
-e "GITHUB_TOKEN=$GITHUB_TOKEN"
-e "RALPH_TASK_ID=$task_id"
--label "ralph.project=$project_name"
--label "ralph.folder=$project_root"
)
if [ -d "$project_root/.ralph" ]; then
docker_args+=(-v "$project_root/.ralph:/workspace/.ralph:ro")
fi
# Mount .env file if it exists (for pnpm install, etc.)
if [ -f "$project_root/.env" ]; then
docker_args+=(-v "$project_root/.env:/workspace/.env:ro")
fi
# Mount Docker socket if it exists (for pnpm dx, docker compose, etc.)
if [ -S /var/run/docker.sock ]; then
docker_args+=(-v "/var/run/docker.sock:/var/run/docker.sock")
# Run as root to access Docker socket (socket permissions don't transfer well)
# The agent tools (opencode/claude) handle their own security
docker_args+=(--user root)
# Use host network so container can reach localhost ports (e.g., databases)
docker_args+=(--network host)
fi
# Add ANTHROPIC_API_KEY if set
if [ -n "$ANTHROPIC_API_KEY" ]; then
docker_args+=(-e "ANTHROPIC_API_KEY=$ANTHROPIC_API_KEY")
fi
local opencode_auth_file="$HOME/.local/share/opencode/auth.json"
if [ -f "$opencode_auth_file" ]; then
docker_args+=(-v "$opencode_auth_file:/home/ralph/.local/share/opencode/auth.json:ro")
fi
local opencode_config_dir="$HOME/.config/opencode"
if [ -d "$opencode_config_dir" ]; then
docker_args+=(-v "$opencode_config_dir:/home/ralph/.config/opencode-host:ro")
# If commands/skills are symlinks, also mount their real paths
# so the entrypoint can follow them
local commands_dir="$opencode_config_dir/commands"
if [ -L "$commands_dir" ]; then
local real_commands=$(readlink -f "$commands_dir")
if [ -d "$real_commands" ]; then
docker_args+=(-v "$real_commands:$real_commands:ro")
fi
fi
local skills_dir="$opencode_config_dir/skills"
if [ -L "$skills_dir" ]; then
local real_skills=$(readlink -f "$skills_dir")
if [ -d "$real_skills" ]; then
docker_args+=(-v "$real_skills:$real_skills:ro")
fi
fi
fi
local claude_config_dir="$HOME/.config/claude"
if [ -d "$claude_config_dir" ]; then
docker_args+=(-v "$claude_config_dir:/home/ralph/.config/claude:ro")
fi
local claude_anthropic_dir="$HOME/.config/anthropic"
if [ -d "$claude_anthropic_dir" ]; then
docker_args+=(-v "$claude_anthropic_dir:/home/ralph/.config/anthropic:ro")
fi
local claude_home_dir="$HOME/.claude"
if [ -d "$claude_home_dir" ]; then
docker_args+=(-v "$claude_home_dir:/home/ralph/.claude:ro")
fi
# Add image and entrypoint args
docker_args+=("$image_name")
if [ -n "$task_type" ]; then
docker_args+=("--$task_type" "$task_value")
fi
if [ -n "$agent_cli_override" ]; then
docker_args+=("--cli" "$agent_cli_override")
fi
if [ -n "$model_override" ]; then
docker_args+=("--model" "$model_override")
fi
log_info "Starting container: $cname"
log_info "Project: $project_name"
if [ -n "$task_type" ]; then
log_info "Task: $task_type = $task_value"
else
log_info "Task: auto (config)"
fi
log_info "Resources: $cpus CPUs, $memory memory"
docker "${docker_args[@]}"
log_success "Container started: $cname"
echo ""
echo "View logs: ralph.sh logs $task_id"
echo "Follow logs: ralph.sh logs -f $task_id"
echo "Stop: ralph.sh stop $task_id"
}
# Format seconds into human readable time (e.g., "5m", "1h 23m", "2d 5h")
format_duration() {
local seconds=$1
if [ "$seconds" -lt 60 ]; then
echo "${seconds}s"
elif [ "$seconds" -lt 3600 ]; then
echo "$((seconds / 60))m"
elif [ "$seconds" -lt 86400 ]; then
local hours=$((seconds / 3600))
local mins=$(((seconds % 3600) / 60))
if [ "$mins" -gt 0 ]; then
echo "${hours}h ${mins}m"
else
echo "${hours}h"
fi
else
local days=$((seconds / 86400))
local hours=$(((seconds % 86400) / 3600))
echo "${days}d ${hours}h"
fi
}
# Get time since last log output in seconds
get_idle_seconds() {
local container=$1
local last_log_time=$(docker logs --timestamps "$container" 2>&1 | tail -1 | cut -d' ' -f1 | sed 's/Z$//')
if [ -n "$last_log_time" ] && [ "$last_log_time" != "" ]; then
# Convert ISO timestamp to epoch
local last_epoch=$(date -j -f "%Y-%m-%dT%H:%M:%S" "${last_log_time%%.*}" "+%s" 2>/dev/null || echo "")
if [ -n "$last_epoch" ]; then
local now_epoch=$(date "+%s")
echo $((now_epoch - last_epoch))
return
fi
fi
echo "0"
}
# Check if agent is waiting for user input based on recent log output
# Returns: "waiting" if permission/input prompt detected, "active" otherwise
check_waiting_state() {
local container=$1
# Get last 20 lines of logs and check for common prompt patterns
local recent_logs=$(docker logs "$container" 2>&1 | tail -20)
# Patterns that indicate waiting for user input
if echo "$recent_logs" | grep -qE '\[Y/n\]|\[y/N\]|Allow\?|Approve\?|yes/no|Confirm\?|Continue\?|Press Enter|waiting for|ask about this'; then
echo "waiting"
else
echo "active"
fi
}
cmd_list() {
echo ""
printf "%-12s %-12s %-10s %-10s %-6s %s\n" "PROJECT" "STATUS" "RUNNING" "IDLE" "TASK" "FOLDER"
printf "%-12s %-12s %-10s %-10s %-6s %s\n" "────────────" "────────────" "──────────" "──────────" "──────" "────────────────"
docker ps -a --filter "name=${CONTAINER_PREFIX}-" --format '{{.Names}}\t{{.Status}}' | while IFS=$'\t' read -r name status; do
# Extract task from container name (last part after project name)
task="${name##*-}"
# Get project from label, or extract from image name
local project=$(docker inspect "$name" --format '{{index .Config.Labels "ralph.project"}}' 2>/dev/null)
if [ -z "$project" ] || [ "$project" = "<no value>" ]; then
project=$(docker inspect "$name" --format '{{.Config.Image}}' 2>/dev/null | sed 's/^ralph-//')
fi
# Get folder from label (if available)
local folder=$(docker inspect "$name" --format '{{index .Config.Labels "ralph.folder"}}' 2>/dev/null)
if [ -z "$folder" ] || [ "$folder" = "<no value>" ]; then
folder="-"
else
folder=$(basename "$folder")
fi
local idle_time="-"
local uptime="-"
# Parse status
if [[ "$status" == *"Up"* ]]; then
uptime=$(echo "$status" | sed 's/Up //' | sed 's/ (.*)//')
# Check if agent process is running
agent_running=$(docker exec "$name" ps -o comm= 2>/dev/null | grep -E "^(opencode|claude|node)$" | head -1)
if [ -n "$agent_running" ]; then
# Agent process exists - check how long since last output
local idle_secs=$(get_idle_seconds "$name")
idle_time=$(format_duration "$idle_secs")
# Check if waiting for user input (permission prompt, etc.)
local waiting_state=$(check_waiting_state "$name")
if [ "$waiting_state" = "waiting" ]; then
state="${BLUE}⏸ waiting${NC}"
elif [ "$idle_secs" -gt 120 ]; then
state="${BLUE}⏸ idle${NC}"
else
state="${YELLOW}⚡ working${NC}"
fi
else
state="${GREEN}✓ done${NC}"
fi
elif [[ "$status" == *"Exited (0)"* ]]; then
state="${GREEN}✓ done${NC}"
else
state="${RED}✗ failed${NC}"
fi
printf "%-12s ${state}%-2s %-10s %-10s %-6s %s\n" "$project" "" "$uptime" "$idle_time" "$task" "$folder"
done
echo ""
}
cmd_logs() {
local config_dir
config_dir=$(find_ralph_config) || true
local project_name=""
if [ -n "$config_dir" ]; then
project_name=$(get_project_name "$config_dir")
fi
local follow=false
local task_id=""
local collected_digits=""
while [[ $# -gt 0 ]]; do
case $1 in
-f|--follow)