-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathlaunch.sh
More file actions
executable file
·992 lines (893 loc) · 37.6 KB
/
Copy pathlaunch.sh
File metadata and controls
executable file
·992 lines (893 loc) · 37.6 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
#!/bin/bash
set -euo pipefail
# Create bare repos, build image, launch N agent containers.
# Usage: ./launch.sh {start|stop|logs N|status|wait|post-process|interactive}
SWARM_DIR="$(cd "$(dirname "$0")" && pwd)"
if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then
cat <<HELP
Usage: $0 [COMMAND] [OPTIONS]
Orchestrate coding agents in Docker containers.
Default command is 'start' when none is specified.
Commands:
start [OPTIONS] Build image, create bare repo, launch agents.
stop Stop all running agent containers.
logs N Tail logs for agent N (default: 1).
status Show running/stopped state for each agent.
wait Wait for already-started numbered agents,
then post-process and harvest. Does not
start agents.
post-process Run only the post-processing agent, then
harvest.
interactive PROFILE Start an interactive driver session from a
named agent profile.
chat PROFILE Alias for interactive PROFILE.
shell PROFILE Start an interactive shell from a named
agent profile.
Start options:
--dashboard Open the TUI dashboard after launch.
Interactive options:
--agent NAME Select agents[].name explicitly.
--agent-index N Select the Nth agents[] entry.
--shell Open a shell instead of the driver UI.
--chat Open the driver UI (default).
Environment:
ANTHROPIC_API_KEY API key (required unless OAuth).
CLAUDE_CODE_OAUTH_TOKEN OAuth token for subscription auth.
SWARM_CONFIG Path to swarmfile (or place swarm.json in repo root).
SWARM_TITLE Dashboard title override.
SWARM_SKIP_DEP_CHECK Set to 1 to silence version warnings.
HELP
exit 0
fi
source "$SWARM_DIR/lib/check-deps.sh"
check_deps git jq docker
# shellcheck source=lib/project.sh
source "$SWARM_DIR/lib/project.sh"
REPO_ROOT="$(git rev-parse --show-toplevel)"
PROJECT_RAW="$(basename "$REPO_ROOT")"
PROJECT="$(swarm_project_id "$PROJECT_RAW")"
SWARM_RUN_HASH="$(git -C "$REPO_ROOT" rev-parse --short=7 HEAD 2>/dev/null || echo "unknown")"
SWARM_RUN_BRANCH="$(git -C "$REPO_ROOT" rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")"
SWARM_RUN_CONTEXT="${PROJECT_RAW}@${SWARM_RUN_HASH} (${SWARM_RUN_BRANCH})"
BARE_REPO="/tmp/${PROJECT}-upstream.git"
IMAGE_NAME="${PROJECT}-agent"
# Expand a single $VAR reference from the host environment.
# Supports "$VAR" (entire value is a reference) only -- not inline
# interpolation. Returns the original string if no match.
expand_env_ref() {
local val="$1"
if [[ "$val" =~ ^\$([A-Za-z_][A-Za-z_0-9]*)$ ]]; then
local varname="${BASH_REMATCH[1]}"
printf '%s' "${!varname:-}"
else
printf '%s' "$val"
fi
}
# Docker containers may create files owned by a different UID inside
# bind-mounted host directories. Plain rm -rf fails without root.
# Use a throwaway Alpine container (Docker is already required) so
# we never need sudo/su -c.
rm_docker_dir() {
local dir="$1"
[ -d "$dir" ] || return 0
local parent base
parent="$(dirname "$dir")"
base="$(basename "$dir")"
docker run --rm -v "${parent}:${parent}" alpine \
rm -rf "${parent}/${base}" 2>/dev/null \
|| rm -rf "$dir" 2>/dev/null || true
}
# Compute the comma-separated SWARM_AGENTS build-arg from a config:
# the union of every agent group's driver and the post-process driver.
# Used as a Dockerfile build-arg to gate per-CLI install layers; missing
# a driver here is what produces "command not found" inside the agent.
compute_swarm_agents() {
local cfg="$1"
local default_drv seen=" " out="" drv
default_drv=$(jq -r '.driver // "claude-code"' "$cfg")
while IFS= read -r drv; do
[ -z "$drv" ] && drv="$default_drv"
[[ "$seen" == *" $drv "* ]] && continue
seen+="$drv "
out="${out:+${out},}${drv}"
done < <(jq -r '.agents[]? | (.driver // "")' "$cfg")
local pp_drv
pp_drv=$(jq -r '.post_process.driver // .driver // "claude-code"' "$cfg")
if [ -n "$pp_drv" ] && [[ "$seen" != *" $pp_drv "* ]]; then
out="${out:+${out},}${pp_drv}"
fi
printf '%s' "$out"
}
# Build (or rebuild) the agent image with build-args derived from the current
# config. Docker's layer cache makes this a no-op when the args and Dockerfile
# haven't changed; when the driver set or pinned CLI versions change the cache
# invalidates correctly and the right install layer re-runs. Called by
# cmd_start *and* cmd_post_process so a standalone post-process invocation
# never reuses an image built for a different driver set (which silently
# produces exit-127 on first session -- see harness's `agent exited with code
# 127` retry path).
build_image() {
local swarm_agents cc_version codex_version
swarm_agents=$(compute_swarm_agents "$CONFIG_FILE")
cc_version=$(jq -r '.claude_code_version // empty' "$CONFIG_FILE" 2>/dev/null || true)
codex_version=$(jq -r '.codex_cli_version // empty' "$CONFIG_FILE" 2>/dev/null || true)
echo "--- Building agent image (agents: ${swarm_agents}) ---"
docker build -t "$IMAGE_NAME" \
--build-arg "SWARM_AGENTS=${swarm_agents}" \
${cc_version:+--build-arg "CLAUDE_CODE_VERSION=${cc_version}"} \
${codex_version:+--build-arg "CODEX_CLI_VERSION=${codex_version}"} \
-f "$SWARM_DIR/Dockerfile" "$SWARM_DIR"
}
create_bare_repo() {
local label="${1:-bare repo}"
echo "--- Creating ${label} ---"
rm_docker_dir "$BARE_REPO"
git clone --bare "$REPO_ROOT" "$BARE_REPO"
git -C "$BARE_REPO" branch agent-work HEAD 2>/dev/null || true
git -C "$BARE_REPO" symbolic-ref HEAD refs/heads/agent-work
git -C "$BARE_REPO" config core.sharedRepository world
chmod -R a+rwX "$BARE_REPO"
}
ensure_bare_repo_for_interactive() {
if [ ! -d "$BARE_REPO" ]; then
create_bare_repo "bare repo for interactive session"
return
fi
local bare_head local_head
bare_head=$(git -C "$BARE_REPO" rev-parse --verify --quiet \
refs/heads/agent-work 2>/dev/null || true)
local_head=$(git rev-parse HEAD 2>/dev/null || true)
if [ -n "$bare_head" ] && [ "$bare_head" != "$local_head" ] \
&& git merge-base --is-ancestor "$bare_head" HEAD 2>/dev/null; then
echo "ERROR: ${BARE_REPO} is stale (agent-work" \
"${bare_head:0:7} behind local HEAD" \
"${local_head:0:7})." >&2
echo " Remove it to start from current HEAD:" >&2
echo " rm -rf ${BARE_REPO}" >&2
exit 1
fi
}
mirror_submodules() {
cd "$REPO_ROOT"
git submodule foreach --quiet 'echo "$name|$toplevel/.git/modules/$sm_path"' | \
while IFS='|' read -r name gitdir; do
local safe_name mirror
safe_name="${name//\//_}"
mirror="/tmp/${PROJECT}-mirror-${safe_name}.git"
rm_docker_dir "$mirror"
echo "--- Mirroring submodule: ${name} ---"
git clone --bare "$gitdir" "$mirror"
chmod -R a+rwX "$mirror"
done
}
write_mirror_volume_file() {
local output_file="$1"
cd "$REPO_ROOT"
git submodule foreach --quiet 'echo "$name"' 2>/dev/null | \
while read -r name; do
local safe_name mirror
safe_name="${name//\//_}"
mirror="/tmp/${PROJECT}-mirror-${safe_name}.git"
[ -d "$mirror" ] || continue
echo "-v ${mirror}:/mirrors/${name}:ro"
done > "$output_file"
}
read_volume_file() {
local input_file="$1"
while read -r line; do
# shellcheck disable=SC2206
[ -n "$line" ] && MIRROR_ARGS+=($line)
done < "$input_file"
}
available_drivers() {
find "$SWARM_DIR/lib/drivers" -type f -name '*.sh' \
-exec basename {} .sh \; | tr '\n' ' '
}
CONFIG_FILE="${SWARM_CONFIG:-}"
if [ -z "$CONFIG_FILE" ] && [ -f "$REPO_ROOT/swarm.json" ]; then
CONFIG_FILE="$REPO_ROOT/swarm.json"
fi
if [ -z "$CONFIG_FILE" ]; then
echo "ERROR: No swarmfile found. Create swarm.json in your repo root or set SWARM_CONFIG." >&2
exit 1
fi
if [ ! -f "$CONFIG_FILE" ]; then
echo "ERROR: Swarmfile ${CONFIG_FILE} not found." >&2
exit 1
fi
SWARM_PROMPT=$(jq -r '.prompt // empty' "$CONFIG_FILE")
SWARM_SETUP=$(jq -r '.setup // empty' "$CONFIG_FILE")
MAX_IDLE=$(jq -r '.max_idle // 3' "$CONFIG_FILE")
INJECT_GIT_RULES=$(jq -r 'if has("inject_git_rules") then .inject_git_rules else true end' "$CONFIG_FILE")
GIT_USER_NAME=$(jq -r '.git_user.name // "swarm-agent"' "$CONFIG_FILE")
GIT_USER_EMAIL=$(jq -r '.git_user.email // "agent@swarm.local"' "$CONFIG_FILE")
GIT_SIGNING_KEY=$(jq -r '.git_user.signing_key // empty' "$CONFIG_FILE")
GIT_SIGNING_KEY="$(expand_env_ref "$GIT_SIGNING_KEY")"
# Resolve signing key path and build volume mount.
SIGNING_KEY_ARGS=()
if [ -n "$GIT_SIGNING_KEY" ]; then
GIT_SIGNING_KEY="${GIT_SIGNING_KEY/#\~/$HOME}"
if [ ! -f "$GIT_SIGNING_KEY" ]; then
echo "ERROR: signing key not found: $GIT_SIGNING_KEY" >&2
exit 1
fi
SIGNING_KEY_ARGS=(-v "${GIT_SIGNING_KEY}:/etc/swarm/signing_key:ro")
fi
NUM_AGENTS=$(jq '[.agents[]? | (.count // 0)] | add // 0' "$CONFIG_FILE")
SWARM_DRIVER_DEFAULT=$(jq -r '.driver // "claude-code"' "$CONFIG_FILE")
MAX_RETRY_WAIT=$(jq -r '.max_retry_wait // 0' "$CONFIG_FILE")
DOCKER_EXTRA_ARGS=()
while IFS= read -r _da; do
[ -n "$_da" ] && DOCKER_EXTRA_ARGS+=("$_da")
done < <(jq -r '.docker_args[]?' "$CONFIG_FILE" 2>/dev/null)
parse_start_args() {
OPEN_DASHBOARD=false
while [ $# -gt 0 ]; do
case "$1" in
--dashboard)
OPEN_DASHBOARD=true
shift ;;
*)
echo "Unknown start option: $1" >&2
echo "Try '$0 --help' for more." >&2
exit 1 ;;
esac
done
}
print_interactive_profiles() {
jq -r '.driver as $dd | .agents | to_entries[] |
"\(.key + 1)|\(.value.name // "")|\(.value.model // "")|" +
"\(.value.driver // $dd // "claude-code")"' \
"$CONFIG_FILE" | while IFS='|' read -r idx name model driver; do
if [ -n "$name" ]; then
printf ' - %s (index %s, %s, %s)\n' \
"$name" "$idx" "${model:-model unset}" "$driver"
else
printf ' - --agent-index %s (%s, %s)\n' \
"$idx" "${model:-model unset}" "$driver"
fi
done >&2
}
select_interactive_profile() {
local selector="$1" selector_index="$2" output_file="$3"
local selected count
if [ -n "$selector_index" ]; then
if ! [[ "$selector_index" =~ ^[0-9]+$ ]] \
|| [ "$selector_index" -lt 1 ]; then
echo "ERROR: --agent-index must be a positive integer." >&2
exit 1
fi
selected=$(jq -c --argjson idx "$((selector_index - 1))" \
'.agents[$idx] // empty' "$CONFIG_FILE")
if [ -z "$selected" ] || [ "$selected" = "null" ]; then
echo "ERROR: no agent at index ${selector_index}." >&2
print_interactive_profiles
exit 1
fi
printf '%s\n' "$selected" > "$output_file"
return
fi
if [ -z "$selector" ]; then
local named_count agent_count
named_count=$(jq '[.agents[] | select(.name? and (.name | length > 0))] | length' \
"$CONFIG_FILE")
agent_count=$(jq '.agents | length' "$CONFIG_FILE")
if [ "$named_count" -eq 1 ]; then
selector=$(jq -r '.agents[] | select(.name? and (.name | length > 0)) | .name' \
"$CONFIG_FILE")
elif [ "$agent_count" -eq 1 ]; then
selector_index=1
select_interactive_profile "$selector" "$selector_index" "$output_file"
return
else
echo "ERROR: choose an interactive profile." >&2
echo "Use '$0 interactive NAME' or '$0 interactive --agent-index N'." >&2
echo "Available profiles:" >&2
print_interactive_profiles
exit 1
fi
fi
count=$(jq --arg name "$selector" \
'[.agents[] | select((.name // "") == $name)] | length' \
"$CONFIG_FILE")
if [ "$count" -eq 0 ]; then
echo "ERROR: no agent profile named '${selector}'." >&2
echo "Available profiles:" >&2
print_interactive_profiles
exit 1
fi
if [ "$count" -gt 1 ]; then
echo "ERROR: agent profile name '${selector}' is not unique." >&2
exit 1
fi
jq -c --arg name "$selector" \
'.agents[] | select((.name // "") == $name)' \
"$CONFIG_FILE" > "$output_file"
}
cmd_interactive() {
local mode="$1"; shift
local selector="" selector_index=""
while [ $# -gt 0 ]; do
case "$1" in
--agent)
selector="${2:-}"
if [ -z "$selector" ]; then
echo "ERROR: --agent requires a name." >&2
exit 1
fi
shift 2 ;;
--agent-index)
selector_index="${2:-}"
if [ -z "$selector_index" ]; then
echo "ERROR: --agent-index requires a number." >&2
exit 1
fi
shift 2 ;;
--shell)
mode="shell"
shift ;;
--chat)
mode="chat"
shift ;;
-h|--help)
cat <<HELP
Usage: $0 interactive [--agent NAME | --agent-index N] [--shell]
$0 chat [--agent NAME | --agent-index N]
$0 shell [--agent NAME | --agent-index N]
Start one human-guided container from an agents[] profile.
HELP
exit 0 ;;
*)
if [ -n "$selector" ]; then
echo "ERROR: multiple interactive profiles supplied." >&2
exit 1
fi
selector="$1"
shift ;;
esac
done
local profile_file
profile_file="/tmp/${PROJECT}-interactive-profile-$$.json"
select_interactive_profile "$selector" "$selector_index" "$profile_file"
local profile_name profile_label safe_profile short_id branch name
local agent_model agent_base_url agent_api_key agent_effort agent_auth
local agent_context agent_prompt agent_auth_token agent_tag agent_driver
profile_name=$(jq -r '.name // empty' "$profile_file")
profile_label="$profile_name"
if [ -z "$profile_label" ]; then
profile_label="agent-${selector_index:-1}"
fi
safe_profile="$(swarm_project_id "$profile_label")"
safe_profile="${safe_profile:0:32}"
short_id="$(date -u +%Y%m%d%H%M%S)-${RANDOM}"
branch="swarm/${SWARM_RUN_HASH}/interactive-${safe_profile}-${short_id}"
name="${IMAGE_NAME}-interactive-${safe_profile}-${short_id}"
if ! git check-ref-format --branch "$branch" >/dev/null 2>&1; then
echo "ERROR: invalid interactive branch name: ${branch}" >&2
exit 1
fi
agent_model=$(jq -r '.model // empty' "$profile_file")
agent_base_url=$(jq -r '.base_url // empty' "$profile_file")
agent_api_key=$(jq -r '.api_key // empty' "$profile_file")
agent_api_key="$(expand_env_ref "$agent_api_key")"
agent_effort=$(jq -r '.effort // empty' "$profile_file")
agent_auth=$(jq -r '.auth // empty' "$profile_file")
agent_context=$(jq -r '.context // empty' "$profile_file")
agent_context="${agent_context:-full}"
agent_prompt=$(jq -r '.prompt // empty' "$profile_file")
agent_auth_token=$(jq -r '.auth_token // empty' "$profile_file")
agent_auth_token="$(expand_env_ref "$agent_auth_token")"
agent_tag=$(jq -r '.tag // empty' "$profile_file")
if [ -z "$agent_tag" ]; then
agent_tag=$(jq -r '.tag // empty' "$CONFIG_FILE")
fi
agent_tag="$(expand_env_ref "$agent_tag")"
agent_driver=$(jq -r --arg dd "$SWARM_DRIVER_DEFAULT" \
'.driver // $dd // "claude-code"' "$profile_file")
agent_driver="${agent_driver:-$SWARM_DRIVER_DEFAULT}"
if [ ! -f "$SWARM_DIR/lib/drivers/${agent_driver}.sh" ]; then
echo "ERROR: unknown driver: ${agent_driver}" >&2
echo "Available drivers: $(available_drivers)" >&2
exit 1
fi
# shellcheck source=lib/drivers/claude-code.sh
source "$SWARM_DIR/lib/drivers/${agent_driver}.sh"
agent_model="${agent_model:-$(agent_default_model)}"
local effective_prompt="${agent_prompt:-$SWARM_PROMPT}"
if [ -n "$effective_prompt" ] && [ ! -f "$REPO_ROOT/$effective_prompt" ]; then
echo "ERROR: prompt '${effective_prompt}' not found." >&2
exit 1
fi
ensure_bare_repo_for_interactive
mirror_submodules
build_image
local vols_file="/tmp/${PROJECT}-interactive-vols.txt"
write_mirror_volume_file "$vols_file"
MIRROR_ARGS=()
read_volume_file "$vols_file"
rm -f "$vols_file" "$profile_file"
local EXTRA_ENV=()
while IFS= read -r _ae; do
[ -n "$_ae" ] && EXTRA_ENV+=("$_ae")
done < <(agent_docker_auth "$agent_api_key" "$agent_auth_token" \
"$agent_auth" "$agent_base_url")
if [ -n "$agent_effort" ]; then
while IFS= read -r _de; do
[ -n "$_de" ] && EXTRA_ENV+=("$_de")
done < <(agent_docker_env "$agent_effort")
fi
docker rm -f "$name" 2>/dev/null || true
echo "--- Starting interactive ${profile_label} (${agent_model}) ---"
echo "Branch: ${branch}"
docker run -it \
--name "$name" \
-v "${BARE_REPO}:/upstream:rw" \
"${MIRROR_ARGS[@]+"${MIRROR_ARGS[@]}"}" \
"${SIGNING_KEY_ARGS[@]+"${SIGNING_KEY_ARGS[@]}"}" \
"${DOCKER_EXTRA_ARGS[@]+"${DOCKER_EXTRA_ARGS[@]}"}" \
"${EXTRA_ENV[@]+"${EXTRA_ENV[@]}"}" \
-e "SWARM_MODEL=${agent_model}" \
-e "SWARM_EFFORT=${agent_effort}" \
-e "CLAUDE_MODEL=${agent_model}" \
-e "SWARM_PROMPT=${effective_prompt}" \
-e "SWARM_SETUP=${SWARM_SETUP}" \
-e "GIT_USER_NAME=${GIT_USER_NAME}" \
-e "GIT_USER_EMAIL=${GIT_USER_EMAIL}" \
-e "INJECT_GIT_RULES=${INJECT_GIT_RULES}" \
-e "AGENT_ID=interactive-${safe_profile}" \
-e "SWARM_TAG=${agent_tag}" \
-e "SWARM_CONTEXT=${agent_context}" \
-e "SWARM_DRIVER=${agent_driver}" \
-e "SWARM_RUN_CONTEXT=${SWARM_RUN_CONTEXT}" \
-e "SWARM_CFG_PROMPT=${effective_prompt}" \
-e "SWARM_CFG_SETUP=${SWARM_SETUP}" \
-e "SWARM_INTERACTIVE_BRANCH=${branch}" \
-e "SWARM_INTERACTIVE_PROFILE=${profile_label}" \
-e "SWARM_INTERACTIVE_MODE=${mode}" \
--entrypoint /interactive.sh \
"$IMAGE_NAME"
}
cmd_start() {
# Top-level prompt is optional when every agent group defines its own.
local all_groups_have_prompt
all_groups_have_prompt=$(jq \
'[.agents[] | has("prompt") and (.prompt | length > 0)] | all' \
"$CONFIG_FILE")
if [ -z "$SWARM_PROMPT" ] && [ "$all_groups_have_prompt" != "true" ]; then
echo "ERROR: 'prompt' is missing in ${CONFIG_FILE} (required when not every agent group specifies its own)." >&2
exit 1
fi
if [ -n "$SWARM_PROMPT" ] && [ ! -f "$REPO_ROOT/$SWARM_PROMPT" ]; then
echo "ERROR: prompt '${SWARM_PROMPT}' not found." >&2
exit 1
fi
# Validate per-group prompt overrides.
local group_prompts
group_prompts=$(jq -r '[.agents[].prompt // empty] | unique[]' \
"$CONFIG_FILE" 2>/dev/null || true)
while IFS= read -r gp; do
[ -z "$gp" ] && continue
if [ ! -f "$REPO_ROOT/$gp" ]; then
echo "ERROR: per-group prompt ${gp} not found." >&2
exit 1
fi
done <<< "$group_prompts"
# Refuse to overwrite a bare repo that diverges from local HEAD.
# Distinguish two directions so the message leads with the remediation
# that actually works. The `--is-ancestor` check runs in the local
# repo, not in the bare: in the "local ahead" case LOCAL_HEAD is not
# in the bare's object db, so running the check in the bare would
# always return non-zero and collapse the stale case into the
# unharvested branch. Running in local works across all three cases
# because bare's objects are either (a) still in local (inherited at
# clone time, so ancestry is resolvable -> stale) or (b) only in
# bare (agent-produced post-clone, so BARE_HEAD errors out here ->
# unharvested, which also catches the truly-divergent case).
if [ -d "$BARE_REPO" ]; then
BARE_HEAD=$(git -C "$BARE_REPO" rev-parse --verify --quiet refs/heads/agent-work 2>/dev/null || true)
LOCAL_HEAD=$(git rev-parse HEAD 2>/dev/null || true)
if [ -n "$BARE_HEAD" ] && [ "$BARE_HEAD" != "$LOCAL_HEAD" ]; then
if git merge-base --is-ancestor "$BARE_HEAD" HEAD 2>/dev/null; then
echo "ERROR: ${BARE_REPO} is stale (agent-work" \
"${BARE_HEAD:0:7} behind local HEAD" \
"${LOCAL_HEAD:0:7})." >&2
echo " Remove it to start a fresh run from" \
"current HEAD:" >&2
echo " rm -rf ${BARE_REPO}" >&2
else
echo "ERROR: ${BARE_REPO} has unharvested agent" \
"commits (agent-work ${BARE_HEAD:0:7} vs local" \
"HEAD ${LOCAL_HEAD:0:7})." >&2
echo " Run harvest.sh first, or if you've" \
"already integrated those commits:" >&2
echo " rm -rf ${BARE_REPO}" >&2
fi
exit 1
fi
fi
create_bare_repo "bare repo"
# Mirror each submodule so containers can init without network.
mirror_submodules
# Build per-agent config (model|base_url|api_key|effort|auth|context|prompt|auth_token|tag|driver per line).
# Uses pipe delimiter because bash IFS=$'\t' collapses consecutive tabs.
AGENTS_CFG="/tmp/${PROJECT}-agents.cfg"
jq -r '.tag as $dt | .driver as $dd |
.agents[] | range(.count // 0) as $i |
[.model, (.base_url // ""), (.api_key // ""), (.effort // ""), (.auth // ""), (.context // ""), (.prompt // ""), (.auth_token // ""), (.tag // $dt // ""), (.driver // $dd // "")] | join("|")' \
"$CONFIG_FILE" > "$AGENTS_CFG"
# Preflight: validate all referenced drivers exist before
# spending time on image build and container startup.
local _bad_drivers="" _checked_drivers=" "
while IFS='|' read -r _ _ _ _ _ _ _ _ _ _drv; do
_drv="${_drv:-${SWARM_DRIVER_DEFAULT}}"
[[ "$_checked_drivers" == *" $_drv "* ]] && continue
_checked_drivers+="$_drv "
if [ ! -f "$SWARM_DIR/lib/drivers/${_drv}.sh" ]; then
_bad_drivers+=" - ${_drv}\n"
fi
done < "$AGENTS_CFG"
if [ -n "$_bad_drivers" ]; then
printf "ERROR: unknown driver(s):\n%b" "$_bad_drivers" >&2
echo "Available drivers: $(available_drivers)" >&2
exit 1
fi
build_image
# Build mirror volume args from discovered submodules.
write_mirror_volume_file "/tmp/${PROJECT}-mirror-vols.txt"
# Read mirror volume mounts (shared across all containers).
MIRROR_ARGS=()
read_volume_file "/tmp/${PROJECT}-mirror-vols.txt"
AGENT_IDX=0
while IFS='|' read -r agent_model agent_base_url agent_api_key agent_effort agent_auth agent_context agent_prompt agent_auth_token agent_tag agent_driver; do
AGENT_IDX=$((AGENT_IDX + 1))
NAME="${IMAGE_NAME}-${AGENT_IDX}"
docker rm -f "$NAME" 2>/dev/null || true
agent_api_key="$(expand_env_ref "$agent_api_key")"
agent_auth_token="$(expand_env_ref "$agent_auth_token")"
agent_tag="$(expand_env_ref "$agent_tag")"
agent_context="${agent_context:-full}"
agent_driver="${agent_driver:-${SWARM_DRIVER_DEFAULT}}"
# Source the driver to access agent_docker_env.
# shellcheck source=lib/drivers/claude-code.sh
source "$SWARM_DIR/lib/drivers/${agent_driver}.sh"
local effective_prompt="${agent_prompt:-$SWARM_PROMPT}"
local ctx_label="" prompt_label="" driver_label=""
[ "$agent_context" != "full" ] && ctx_label=" context=${agent_context}"
[ -n "$agent_prompt" ] && prompt_label=" prompt=${agent_prompt}"
[ "$agent_driver" != "claude-code" ] && driver_label=" driver=${agent_driver}"
echo "--- Launching ${NAME} (${agent_model}${agent_effort:+ effort=${agent_effort}}${ctx_label}${prompt_label}${driver_label}) ---"
EXTRA_ENV=()
# Delegate auth credential resolution to the driver.
while IFS= read -r _ae; do
[ -n "$_ae" ] && EXTRA_ENV+=("$_ae")
done < <(agent_docker_auth "$agent_api_key" "$agent_auth_token" "$agent_auth" "$agent_base_url")
local eff="${agent_effort:-}"
if [ -n "$eff" ]; then
while IFS= read -r _de; do
[ -n "$_de" ] && EXTRA_ENV+=("$_de")
done < <(agent_docker_env "$eff")
fi
local price_input="" price_output="" price_cached=""
local _price
_price=$(jq -r --arg m "$agent_model" \
'.pricing[$m] // empty | "\(.input + 0) \(.output + 0) \((.cached // 0) + 0)"' \
"$CONFIG_FILE" 2>/dev/null || true)
if [ -n "$_price" ]; then
read -r price_input price_output price_cached <<< "$_price"
fi
docker run -d \
--name "$NAME" \
-v "${BARE_REPO}:/upstream:rw" \
"${MIRROR_ARGS[@]+"${MIRROR_ARGS[@]}"}" \
"${SIGNING_KEY_ARGS[@]+"${SIGNING_KEY_ARGS[@]}"}" \
"${DOCKER_EXTRA_ARGS[@]+"${DOCKER_EXTRA_ARGS[@]}"}" \
"${EXTRA_ENV[@]+"${EXTRA_ENV[@]}"}" \
-e "SWARM_MODEL=${agent_model}" \
-e "SWARM_EFFORT=${eff}" \
-e "CLAUDE_MODEL=${agent_model}" \
-e "SWARM_PROMPT=${effective_prompt}" \
-e "SWARM_SETUP=${SWARM_SETUP}" \
-e "MAX_IDLE=${MAX_IDLE}" \
-e "MAX_RETRY_WAIT=${MAX_RETRY_WAIT}" \
-e "GIT_USER_NAME=${GIT_USER_NAME}" \
-e "GIT_USER_EMAIL=${GIT_USER_EMAIL}" \
-e "INJECT_GIT_RULES=${INJECT_GIT_RULES}" \
-e "AGENT_ID=${AGENT_IDX}" \
-e "SWARM_TAG=${agent_tag}" \
-e "SWARM_CONTEXT=${agent_context}" \
-e "SWARM_DRIVER=${agent_driver}" \
-e "SWARM_RUN_CONTEXT=${SWARM_RUN_CONTEXT}" \
-e "SWARM_CFG_PROMPT=${effective_prompt}" \
-e "SWARM_CFG_SETUP=${SWARM_SETUP}" \
-e "SWARM_ACTIVITY_TIMEOUT=${SWARM_ACTIVITY_TIMEOUT:-0}" \
-e "SWARM_ACTIVITY_POLL=${SWARM_ACTIVITY_POLL:-10}" \
-e "SWARM_WATCHDOG_GRACE=${SWARM_WATCHDOG_GRACE:-10}" \
${price_input:+-e "SWARM_PRICE_INPUT=${price_input}"} \
${price_output:+-e "SWARM_PRICE_OUTPUT=${price_output}"} \
${price_cached:+-e "SWARM_PRICE_CACHED=${price_cached}"} \
"$IMAGE_NAME"
done < "$AGENTS_CFG"
rm -f "/tmp/${PROJECT}-mirror-vols.txt" "/tmp/${PROJECT}-agents.cfg"
# Write state file so a standalone dashboard can pick up config.
local state_model_summary state_config_label
state_model_summary=$(jq -r \
'(.prompt // "") as $dp | ($dp | split("/") | .[-1] // "" | rtrimstr(".md")) as $dp_stem |
[.agents[] | (.count // 0) as $count | select($count > 0) |
"\($count)x \(.model | split("/") | .[-1])" +
(if .context == "none" then " ctx:bare"
elif .context == "slim" then " ctx:slim"
else "" end) +
(if .prompt and .prompt != $dp then
":" + (.prompt | split("/") | .[-1] | rtrimstr(".md") |
if startswith($dp_stem + "-") then .[$dp_stem | length + 1:] else . end)
else "" end)] | join(", ")' \
"$CONFIG_FILE")
state_config_label=$(basename "$CONFIG_FILE")
local config_title
config_title=$(jq -r '.title // empty' "$CONFIG_FILE" 2>/dev/null || true)
cat > "/tmp/${PROJECT}-swarm.env" <<ENVEOF
SWARM_TITLE="${SWARM_TITLE:-${config_title}}"
SWARM_CONFIG="${CONFIG_FILE}"
SWARM_NUM_AGENTS="${NUM_AGENTS}"
SWARM_MODEL_SUMMARY="${state_model_summary}"
SWARM_CONFIG_LABEL="${state_config_label}"
ENVEOF
echo ""
echo "--- ${NUM_AGENTS} agents launched ---"
echo ""
echo "Monitor:"
echo " $0 status"
echo " $0 logs 1"
echo ""
echo "Stop:"
echo " $0 stop"
echo ""
echo "Bare repo: ${BARE_REPO}"
}
cmd_stop() {
# Default to a 60s grace so the harness's SIGTERM trap has
# time to ship any in-flight local commits via
# `_session_end_push` before docker forces SIGKILL. The 10s
# default that docker ships with cuts the emergency push
# mid-rebase on a busy bare repo. Override via env:
# SWARM_STOP_TIMEOUT=120 ./launch.sh stop
local stop_timeout="${SWARM_STOP_TIMEOUT:-60}"
echo "--- Stopping agents (grace ${stop_timeout}s) ---"
for i in $(seq 1 "$NUM_AGENTS"); do
NAME="${IMAGE_NAME}-${i}"
docker stop -t "$stop_timeout" "$NAME" 2>/dev/null \
&& echo " stopped ${NAME}" \
|| echo " ${NAME} not running"
done
while IFS= read -r NAME; do
[ -n "$NAME" ] || continue
docker stop -t "$stop_timeout" "$NAME" 2>/dev/null \
&& echo " stopped ${NAME}" \
|| echo " ${NAME} not running"
done < <(docker ps -a --format '{{.Names}}' 2>/dev/null \
| grep -E "^${IMAGE_NAME}-interactive-" \
| sort || true)
NAME="${IMAGE_NAME}-post"
docker stop -t "$stop_timeout" "$NAME" 2>/dev/null \
&& echo " stopped ${NAME}" \
|| echo " ${NAME} not running"
rm -f "/tmp/${PROJECT}-swarm.env"
}
cmd_logs() {
local n="${1:-1}"
docker logs -f "${IMAGE_NAME}-${n}"
}
cmd_status() {
for i in $(seq 1 "$NUM_AGENTS"); do
NAME="${IMAGE_NAME}-${i}"
printf "%-30s " "${NAME}:"
docker inspect -f '{{.State.Status}}' "$NAME" 2>/dev/null \
|| echo "not found"
done
while read -r NAME; do
[ -n "$NAME" ] || continue
local env_dump branch profile state
env_dump=$(docker inspect -f \
'{{range .Config.Env}}{{println .}}{{end}}' \
"$NAME" 2>/dev/null || true)
branch=$(printf '%s' "$env_dump" \
| grep '^SWARM_INTERACTIVE_BRANCH=' \
| head -1 | cut -d= -f2- || true)
profile=$(printf '%s' "$env_dump" \
| grep '^SWARM_INTERACTIVE_PROFILE=' \
| head -1 | cut -d= -f2- || true)
state=$(docker inspect -f '{{.State.Status}}' "$NAME" 2>/dev/null \
|| echo "not found")
printf "%-30s " "${NAME}:"
printf "%s" "$state"
[ -n "$profile" ] && printf " profile=%s" "$profile"
[ -n "$branch" ] && printf " branch=%s" "$branch"
printf "\n"
done < <(docker ps -a --format '{{.Names}}' 2>/dev/null \
| grep -E "^${IMAGE_NAME}-interactive-" \
| sort || true)
}
cmd_wait() {
echo "--- Waiting for all agents to finish ---"
while true; do
sleep 10
local all_done=true running=0 exited=0
for i in $(seq 1 "$NUM_AGENTS"); do
local state
state=$(docker inspect -f '{{.State.Status}}' "${IMAGE_NAME}-${i}" 2>/dev/null || echo "not found")
case "$state" in
running) running=$((running + 1)); all_done=false ;;
exited) exited=$((exited + 1)) ;;
esac
done
printf "\r %d running, %d exited " "$running" "$exited"
if $all_done; then
echo ""
echo "All agents finished."
break
fi
done
local pp_prompt
pp_prompt=$(jq -r '.post_process.prompt // empty' "$CONFIG_FILE")
if [ -n "$pp_prompt" ]; then
echo ""
cmd_post_process
return
fi
echo ""
echo "--- Harvesting results ---"
"$SWARM_DIR/harvest.sh"
}
cmd_post_process() {
local pp_prompt pp_model pp_base_url pp_api_key pp_effort pp_auth pp_auth_token pp_tag pp_driver pp_max_idle pp_setup
pp_prompt=$(jq -r '.post_process.prompt // empty' "$CONFIG_FILE")
pp_max_idle=$(jq -r '.post_process.max_idle // .max_idle // 3' "$CONFIG_FILE")
pp_model=$(jq -r '.post_process.model // "claude-opus-4-6"' "$CONFIG_FILE")
pp_base_url=$(jq -r '.post_process.base_url // empty' "$CONFIG_FILE")
pp_api_key=$(jq -r '.post_process.api_key // empty' "$CONFIG_FILE")
pp_api_key="$(expand_env_ref "$pp_api_key")"
pp_auth_token=$(jq -r '.post_process.auth_token // empty' "$CONFIG_FILE")
pp_auth_token="$(expand_env_ref "$pp_auth_token")"
pp_effort=$(jq -r '.post_process.effort // empty' "$CONFIG_FILE")
pp_auth=$(jq -r '.post_process.auth // empty' "$CONFIG_FILE")
pp_tag=$(jq -r '.post_process.tag // .tag // empty' "$CONFIG_FILE")
pp_tag="$(expand_env_ref "$pp_tag")"
pp_driver=$(jq -r '.post_process.driver // .driver // "claude-code"' "$CONFIG_FILE")
# Resolve the post-process setup script. An explicit
# post_process.setup wins (a path runs it, false/empty skips it so a
# heavy top-level setup is not redone); omitting the key inherits
# the top-level setup.
if jq -e '(.post_process // {}) | has("setup")' "$CONFIG_FILE" \
>/dev/null 2>&1; then
pp_setup=$(jq -r '.post_process.setup // ""' "$CONFIG_FILE")
[ "$pp_setup" = "false" ] && pp_setup=""
else
pp_setup="${SWARM_SETUP:-}"
fi
if [ -z "$pp_prompt" ]; then
echo "ERROR: post_process.prompt is not set in ${CONFIG_FILE}." >&2
exit 1
fi
if [ ! -d "$BARE_REPO" ]; then
create_bare_repo "bare repo for post-process"
fi
build_image
local NAME="${IMAGE_NAME}-post"
docker rm -f "$NAME" 2>/dev/null || true
# Build mirror volume args from existing mirrors.
local MIRROR_ARGS=()
write_mirror_volume_file "/tmp/${PROJECT}-pp-vols.txt"
read_volume_file "/tmp/${PROJECT}-pp-vols.txt"
rm -f "/tmp/${PROJECT}-pp-vols.txt"
# Source the driver to access agent_docker_auth / agent_docker_env.
# shellcheck source=lib/drivers/claude-code.sh
source "$SWARM_DIR/lib/drivers/${pp_driver}.sh"
local EXTRA_ENV=()
while IFS= read -r _ae; do
[ -n "$_ae" ] && EXTRA_ENV+=("$_ae")
done < <(agent_docker_auth "$pp_api_key" "$pp_auth_token" "$pp_auth" "$pp_base_url")
if [ -n "$pp_effort" ]; then
while IFS= read -r _de; do
[ -n "$_de" ] && EXTRA_ENV+=("$_de")
done < <(agent_docker_env "$pp_effort")
fi
local price_input="" price_output="" price_cached=""
local _price
_price=$(jq -r --arg m "$pp_model" \
'.pricing[$m] // empty | "\(.input + 0) \(.output + 0) \((.cached // 0) + 0)"' \
"$CONFIG_FILE" 2>/dev/null || true)
if [ -n "$_price" ]; then
read -r price_input price_output price_cached <<< "$_price"
fi
echo "--- Starting post-processing (${pp_model}) ---"
docker run -d \
--name "$NAME" \
-v "${BARE_REPO}:/upstream:rw" \
"${MIRROR_ARGS[@]+"${MIRROR_ARGS[@]}"}" \
"${SIGNING_KEY_ARGS[@]+"${SIGNING_KEY_ARGS[@]}"}" \
"${DOCKER_EXTRA_ARGS[@]+"${DOCKER_EXTRA_ARGS[@]}"}" \
"${EXTRA_ENV[@]+"${EXTRA_ENV[@]}"}" \
-e "SWARM_MODEL=${pp_model}" \
-e "SWARM_EFFORT=${pp_effort}" \
-e "CLAUDE_MODEL=${pp_model}" \
-e "SWARM_PROMPT=${pp_prompt}" \
-e "SWARM_SETUP=${pp_setup}" \
-e "MAX_IDLE=${pp_max_idle}" \
-e "MAX_RETRY_WAIT=${MAX_RETRY_WAIT}" \
-e "GIT_USER_NAME=${GIT_USER_NAME}" \
-e "GIT_USER_EMAIL=${GIT_USER_EMAIL}" \
-e "INJECT_GIT_RULES=${INJECT_GIT_RULES}" \
-e "AGENT_ID=post" \
-e "SWARM_TAG=${pp_tag}" \
-e "SWARM_DRIVER=${pp_driver}" \
-e "SWARM_RUN_CONTEXT=${SWARM_RUN_CONTEXT}" \
-e "SWARM_CFG_PROMPT=${pp_prompt}" \
-e "SWARM_CFG_SETUP=${pp_setup}" \
-e "SWARM_ACTIVITY_TIMEOUT=${SWARM_ACTIVITY_TIMEOUT:-0}" \
-e "SWARM_ACTIVITY_POLL=${SWARM_ACTIVITY_POLL:-10}" \
-e "SWARM_WATCHDOG_GRACE=${SWARM_WATCHDOG_GRACE:-10}" \
${price_input:+-e "SWARM_PRICE_INPUT=${price_input}"} \
${price_output:+-e "SWARM_PRICE_OUTPUT=${price_output}"} \
${price_cached:+-e "SWARM_PRICE_CACHED=${price_cached}"} \
"$IMAGE_NAME"
echo "Post-processing agent launched: ${NAME}"
echo "Waiting for completion..."
while true; do
sleep 10
local state
state=$(docker inspect -f '{{.State.Status}}' "$NAME" 2>/dev/null || echo "not found")
if [ "$state" = "running" ]; then
printf "."
continue
fi
echo ""
echo "Post-processing agent finished (${state})."
break
done
# Capture container exit code BEFORE harvest. Harvest runs unconditionally
# so a crashed agent's in-flight commits still land locally (best-effort
# recovery), but we propagate the failure upward so callers (CI workflows,
# daemons) can refuse to publish partial state.
local exit_code
exit_code=$(docker inspect -f '{{.State.ExitCode}}' "$NAME" 2>/dev/null || echo "1")
echo ""
echo "--- Harvesting results ---"
"$SWARM_DIR/harvest.sh"
if [ "$exit_code" -ne 0 ]; then
echo "WARNING: post-process container exited with code ${exit_code};" \
"any commits harvested may represent partial state." >&2
return "$exit_code"
fi
}
case "${1:-start}" in
start)
shift
parse_start_args "$@"
cmd_start
if $OPEN_DASHBOARD; then
exec "$SWARM_DIR/dashboard.sh"
fi
;;
stop) cmd_stop ;;
logs) cmd_logs "${2:-1}" ;;
status) cmd_status ;;
wait) cmd_wait ;;
post-process) cmd_post_process ;;
interactive)
shift
cmd_interactive chat "$@"
;;
chat)
shift
cmd_interactive chat "$@"
;;
shell)
shift
cmd_interactive shell "$@"
;;
*)
echo "Usage: $0 {start|stop|logs N|status|wait|post-process|interactive}" >&2
echo "Try '$0 --help' for more information." >&2
exit 1
;;
esac