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
|
#!/bin/bash
# ai — agent session launcher (unified aix + hey)
#
# Usage:
# ai Pick the agent first (claude, codex/ChatGPT, or any
# local ollama model), then select one or more projects
# via fzf; each opens in an 'ai' tmux session window.
# Git-aware: fetches, annotates with ↑/↓/dirty, auto-pulls
# clean-and-behind repos before opening. --runtime or
# AI_RUNTIME skips the agent pick.
#
# ai <dir>... Single-project mode. Opens each given directory directly
# in the 'ai' session (new window or switch to existing).
# Use '.' for current directory. Git prep per dir.
#
# ai --runtime <rt> Launch with a different agent CLI: claude (default),
# codex, or local (codex --oss against this machine's
# ollama; model per AI_LOCAL_MODEL, default gpt-oss:120b).
# Also settable via AI_RUNTIME.
#
# ai --helper <dir> Open a SECOND session in a project that already has a
# live one, under the helper-mode.org role contract: reads
# freely, makes only scoped edits, never mutates git, and
# skips git prep because the primary owns pulls. Runs
# agent-roster first — with no other agent live it warns
# and falls back to a normal primary launch (which does
# run git prep). Run it from a terminal of your own: the
# roster excludes its caller's own process ancestry, so
# invoking it from inside an agent session hides that
# session and silently downgrades to a primary launch.
#
# ai --attach Attach to the existing 'ai' session without changes.
#
# ai -h | --help Show this help.
#
# Source: ~/code/rulesets/claude-templates/bin/ai
# Install: make -C ~/code/rulesets install
#
# NOTE: do not enable `set -e`. Several helper functions use
# `[ test ] && action` patterns that legitimately return non-zero when
# the test fails (e.g. maybe_add_candidate when a dir lacks .ai/protocols.org,
# git_status_indicator when a repo is clean). With set -e those exit codes
# would kill the script.
SESSION="ai"
RUNTIME="${AI_RUNTIME:-claude}"
LOCAL_MODEL="${AI_LOCAL_MODEL:-gpt-oss:120b}"
# Map the runtime name to the agent CLI a pane launches. All three take the
# opening instructions as a positional prompt. AGENT_BIN is the binary the
# dependency check probes; AGENT_CMD is the full launch command (the local
# runtime rides codex's open-source provider against the machine's ollama —
# model per AI_LOCAL_MODEL, default gpt-oss:120b, verified on ratio's
# Strix Halo 2026-07-13).
resolve_agent_cmd() {
case "$RUNTIME" in
claude)
AGENT_BIN="claude"
AGENT_CMD="claude"
;;
codex)
AGENT_BIN="codex"
AGENT_CMD="codex"
;;
local)
AGENT_BIN="codex"
AGENT_CMD="codex --oss --local-provider=ollama -m $LOCAL_MODEL"
;;
*)
echo "ai: unknown runtime '$RUNTIME' — valid runtimes: claude, codex, local" >&2
exit 2
;;
esac
}
# One line per launchable agent, claude first (Enter-Enter keeps the old
# muscle memory). Local models appear only when both codex (the CLI that
# drives them) and a live ollama answer; a dead server just drops the lines.
build_runtime_choices() {
command -v claude >/dev/null 2>&1 && echo "claude — Claude Code"
command -v codex >/dev/null 2>&1 && echo "codex — ChatGPT (Codex CLI)"
if command -v codex >/dev/null 2>&1 && command -v ollama >/dev/null 2>&1; then
timeout 3 ollama list 2>/dev/null | tail -n +2 | awk 'NF {print "local:" $1 " — ollama"}'
fi
}
# Interactive runtime pick for the bare-`ai` flow. Sets RUNTIME (and
# LOCAL_MODEL for a local pick) and re-resolves the agent command.
# Returns 1 when the pick is cancelled.
pick_runtime() {
local choice
choice=$(build_runtime_choices | fzf --height=30% --reverse --prompt='agent> ') || return 1
[ -z "$choice" ] && return 1
case "$choice" in
claude*) RUNTIME="claude" ;;
codex*) RUNTIME="codex" ;;
local:*)
RUNTIME="local"
LOCAL_MODEL="${choice#local:}"
LOCAL_MODEL="${LOCAL_MODEL%% *}"
;;
esac
resolve_agent_cmd
}
# Run in the pane's shell just before Claude launches. `stty susp undef` clears
# the tty's SIGTSTP (C-z) character for this pane only, so an accidental C-z is
# passed through to Claude as input rather than suspending the session to the
# shell. Scoped here so C-z keeps working as job control in every other
# terminal, shell, and program.
LAUNCH_PREFIX="stty susp undef; "
# Format the per-project opening line passed to claude. Takes the project
# directory's basename; returns a string of the form
# "This is <host> <name> project. Follow all instructions in .ai/protocols.org."
# Uses uname -n for the host (POSIX, no dependency on the hostname binary
# which isn't installed by default on every distro). The project name
# disambiguates windows when multiple projects share an ai-session.
build_instructions() {
local name="$1"
printf 'This is %s %s project. Follow all instructions in .ai/protocols.org.' "$(uname -n)" "$name"
}
# The opening line for a helper session. Deliberately does NOT name
# protocols.org: a helper must not run normal startup (pulls, rsync, inbox
# processing all belong to the primary), and helper-mode.org sends it to
# protocols.org itself once the role contract is loaded.
build_helper_instructions() {
local name="$1"
printf 'This is %s %s project. You are a helper session: another agent is already live here. Read and follow .ai/workflows/helper-mode.org — it is your role contract. Do not run the normal startup workflow.' \
"$(uname -n)" "$name"
}
usage() {
sed -n '2,34p' "$0" | sed 's|^# \?||'
exit 0
}
check_deps() {
for cmd in fzf tmux "$AGENT_BIN"; do
if ! command -v "$cmd" &>/dev/null; then
echo "ai: $cmd is not installed" >&2
exit 1
fi
done
}
# ---------- pure decision cores (no tmux/git I/O; unit-tested directly) ----------
# Decide what a git-prep pass should do from a repo's already-computed state.
# Inputs: has_upstream (1/0), dirty (1/0), ahead, behind. Echoes one of:
# none — no upstream, or in sync: nothing to do
# pull — clean and purely behind: safe to fast-forward
# report — ahead, dirty, or behind-while-dirty: show a summary, don't pull
_git_prep_action() {
local has_upstream="$1" dirty="$2" ahead="$3" behind="$4"
[ "$has_upstream" -eq 1 ] || {
echo none
return
}
if [ "$dirty" -eq 0 ] && [ "$ahead" -eq 0 ] && [ "$behind" -gt 0 ]; then
echo pull
elif [ "$ahead" -gt 0 ] || [ "$behind" -gt 0 ] || [ "$dirty" -eq 1 ]; then
echo report
else
echo none
fi
}
# Decide what a `--helper` launch actually becomes, from the roster's verdict.
# Input is agent-roster's exit status — 0 alone, 1 others live, 2 unavailable —
# or the literal "absent" when no roster script is installed. Echoes one of:
# helper — confirmed: another agent is live here
# primary — refuted: nobody else is here, so --helper is a no-op
# helper-unverified — the roster couldn't answer
# Unverifiable resolves toward helper on purpose. `--helper` is the operator
# asserting a primary is live, and helper mode is the strictly less destructive
# guess: a helper that turns out to be alone merely does less, while a primary
# that turns out not to be alone runs pulls and rsync under a live session.
_helper_launch_mode() {
case "$1" in
1) echo helper ;;
0) echo primary ;;
*) echo helper-unverified ;;
esac
}
# A helper's agent id: helper-<rand4>, per helper-mode.org's identity rule.
# Four hex digits is enough — the id only has to be unique among the agents
# live in one project at one moment, and the archived session file carries the
# date and time as well. Two draws because bash's RANDOM is 15-bit, so a single
# one would never set the top bit and the first hex digit would always be 0-7.
_helper_id() {
printf 'helper-%04x\n' $(( ((RANDOM << 1) ^ RANDOM) & 0xffff ))
}
# Reduce an id to the characters session-context-path keeps, so the launcher and
# the path resolver agree on what a given id means. This is also a safety fix,
# not just tidiness: the id is interpolated into the command line typed into the
# pane, so an id carrying a space or a ';' would split the assignment off from
# the command and run something else instead of launching the helper.
# printf without a newline on purpose: tr -c would translate a trailing newline
# into an underscore too, silently appending one to every sanitized id.
_sanitize_agent_id() {
printf '%s' "$1" | tr -c 'A-Za-z0-9._-' '_'
printf '\n'
}
# Resolve the id for a helper launch: an explicitly-exported one when it is
# free, otherwise a fresh one.
#
# The reuse check is the load-bearing part. A helper's own pane exports
# AI_AGENT_ID, so `ai --helper` invoked from inside a helper inherits its
# parent's id rather than being given one deliberately. Honoring that blindly
# points two live agents at one .ai/session-context.d/<id>.org, which is the
# lost-update collision the whole helper contract exists to avoid.
_resolve_helper_id() {
local dir="$1"
local want="${AI_AGENT_ID:-}"
local tries=0
if [ -n "$want" ]; then
want="$(_sanitize_agent_id "$want")"
if [ ! -e "$dir/.ai/session-context.d/$want.org" ]; then
printf '%s\n' "$want"
return
fi
echo "ai: agent id '$want' is already live in $(basename "$dir") — assigning a fresh one" >&2
fi
# A minted id gets the same free-anchor check as a supplied one. The odds of
# a chance collision are small, but a guard that only covers the path the
# caller controls leaves the collision it exists to prevent reachable.
# Bounded so a full or unreadable directory can't spin here.
while [ "$tries" -lt 8 ]; do
want="$(_helper_id)"
[ -e "$dir/.ai/session-context.d/$want.org" ] || break
tries=$((tries + 1))
done
printf '%s\n' "$want"
}
# Re-order "name<TAB>wid" lines (stdin) into the launcher's window order:
# non-project windows alphabetically, then project windows alphabetically.
# $1 is a newline-separated list of project window names.
#
# A helper window is named "<project>:<agent-id>", so it matches on the prefix
# before the first colon rather than on the whole name. That keeps it sorted
# next to the project it helps instead of landing among the unrelated windows.
_order_windows() {
local project_names="$1" wname wid others="" projects=""
while IFS=$'\t' read -r wname wid; do
[ -z "$wname" ] && continue
if printf '%s\n' "$project_names" | grep -qxF "$wname" ||
printf '%s\n' "$project_names" | grep -qxF "${wname%%:*}"; then
projects+="${wname}"$'\t'"${wid}"$'\n'
else
others+="${wname}"$'\t'"${wid}"$'\n'
fi
done
others=$(printf '%s' "$others" | sort -t$'\t' -k1,1f)
projects=$(printf '%s' "$projects" | sort -t$'\t' -k1,1f)
printf '%s\n%s\n' "$others" "$projects" | sed '/^$/d'
}
# Emit the window id whose name (field 1 of "name<TAB>wid" stdin) equals $1.
_match_window_id() {
awk -F'\t' -v n="$1" '$1 == n { print $2; exit }'
}
# ---------- shared helpers ----------
attach_session() {
if [ -n "${TMUX:-}" ]; then
tmux switch-client -t "$SESSION"
else
tmux attach-session -t "$SESSION"
fi
}
# Create a window in the ai session, launch claude, return window id.
create_window() {
local dir="$1" name="$2" wid instructions
wid=$(tmux new-window -a -t "$SESSION:{end}" -n "$name" -c "$dir" -P -F '#{window_id}')
sleep 0.1
instructions=$(build_instructions "$name")
tmux send-keys -t "$wid" "${LAUNCH_PREFIX}$AGENT_CMD \"$instructions\"" Enter
echo "$wid"
}
# Add a directory to candidates only if it's a Claude-template project.
maybe_add_candidate() {
local dir="$1"
# The "~/" is a deliberate literal display prefix, re-expanded downstream via
# ${c/#\~/$HOME}; it must not expand here, so SC2088 doesn't apply.
# shellcheck disable=SC2088
[ -f "$dir/.ai/protocols.org" ] && candidates+=("~/${dir#"$HOME"/}")
}
# Build un-annotated candidate list (used by multi_mode and sort_windows).
build_candidates() {
candidates=()
maybe_add_candidate "$HOME/.emacs.d"
maybe_add_candidate "$HOME/.dotfiles"
if [ -d "$HOME/code" ]; then
while IFS= read -r d; do
maybe_add_candidate "$d"
done < <(find "$HOME/code" -maxdepth 1 -mindepth 1 -type d | sort)
fi
if [ -d "$HOME/projects" ]; then
while IFS= read -r d; do
maybe_add_candidate "$d"
done < <(find "$HOME/projects" -maxdepth 1 -mindepth 1 -type d | sort)
fi
}
# Parallel fetch across all current candidates (capped concurrency).
fetch_candidates() {
local max=6 running=0 dir
for c in "${candidates[@]}"; do
dir="${c/#\~/$HOME}"
[ -d "$dir/.git" ] || continue
git -C "$dir" fetch --quiet 2>/dev/null &
running=$((running + 1))
if [ "$running" -ge "$max" ]; then
wait
running=0
fi
done
wait
}
# Resolve the shared state gate installed beside this launcher. Keeping the
# policy in one executable prevents startup, the picker, and wrap-up from
# developing different meanings of "safe to sync."
_git_gate_path() {
local gate="${GIT_WORKTREE_GATE:-}"
[ -n "$gate" ] || gate="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/git-worktree-gate"
[ -x "$gate" ] && printf '%s\n' "$gate"
}
# True (exit 0) when strict wrap would reject the worktree.
_git_is_dirty() {
local dir="$1" gate
gate="$(_git_gate_path)" || return 0
! "$gate" strict "$dir" >/dev/null 2>&1
}
# True (exit 0) when startup sync must stop. Untracked inbox deliveries are
# safe queue input; every tracked, staged, or other untracked change blocks.
_git_blocks_sync() {
local dir="$1" gate
gate="$(_git_gate_path)" || return 0
! "$gate" sync-safe "$dir" >/dev/null 2>&1
}
# Return " (↑N ↓N dirty)" or " (✓)" if clean.
git_status_indicator() {
local dir="$1" upstream ahead=0 behind=0 parts=()
[ -d "$dir/.git" ] || return 0
upstream=$(git -C "$dir" rev-parse --abbrev-ref --symbolic-full-name "@{u}" 2>/dev/null || true)
if [ -n "$upstream" ]; then
ahead=$(git -C "$dir" rev-list --count "$upstream..HEAD" 2>/dev/null || echo 0)
behind=$(git -C "$dir" rev-list --count "HEAD..$upstream" 2>/dev/null || echo 0)
[ "${ahead:-0}" -gt 0 ] 2>/dev/null && parts+=("↑$ahead")
[ "${behind:-0}" -gt 0 ] 2>/dev/null && parts+=("↓$behind")
else
parts+=("no upstream")
fi
if _git_is_dirty "$dir"; then
if _git_blocks_sync "$dir"; then
parts+=("dirty")
else
parts+=("inbox")
fi
fi
if [ ${#parts[@]} -gt 0 ]; then
local IFS=' '
printf ' (%s)' "${parts[*]}"
else
printf ' (✓)'
fi
}
# Append status annotations to every candidate.
annotate_candidates() {
local dir status annotated=()
for c in "${candidates[@]}"; do
dir="${c/#\~/$HOME}"
status=$(git_status_indicator "$dir")
annotated+=("${c}${status}")
done
candidates=("${annotated[@]}")
}
# Pull if sync-safe, behind, not ahead. Inbox-only queue input is sync-safe.
auto_pull_if_clean() {
local dir="$1" upstream ahead behind
[ -d "$dir/.git" ] || return 0
_git_blocks_sync "$dir" && return 0
upstream=$(git -C "$dir" rev-parse --abbrev-ref --symbolic-full-name "@{u}" 2>/dev/null || true)
[ -z "$upstream" ] && return 0
ahead=$(git -C "$dir" rev-list --count "$upstream..HEAD" 2>/dev/null || echo 0)
behind=$(git -C "$dir" rev-list --count "HEAD..$upstream" 2>/dev/null || echo 0)
# dirty=0 and has_upstream=1 are guaranteed by the early returns above.
[ "$(_git_prep_action 1 0 "${ahead:-0}" "${behind:-0}")" = pull ] &&
git -C "$dir" pull --ff-only --quiet 2>/dev/null || true
}
# Strip " (annotation)" suffix from fzf output so downstream gets raw paths.
read_selections() {
selected=()
while IFS= read -r line; do
selected+=("${line%% (*}")
done <<<"$1"
}
# Re-order windows: non-project windows at base-index, projects alphabetically after.
sort_windows() {
local windows base_idx project_names="" ordered
base_idx=$(tmux show-option -gv base-index 2>/dev/null || echo 0)
windows=$(tmux list-windows -t "$SESSION" -F '#{window_name}'$'\t''#{window_id}')
build_candidates
for c in "${candidates[@]}"; do
project_names+="$(basename "${c/#\~/$HOME}")"$'\n'
done
ordered=$(printf '%s\n' "$windows" | _order_windows "$project_names")
[ -z "$ordered" ] && return 0
# First pass parks every window above the live range so the second pass can
# reassign the target indices without colliding with a window already there.
local i=900
while IFS=$'\t' read -r _n wid; do
[ -z "$wid" ] && continue
tmux move-window -s "$wid" -t "$SESSION:$i"
i=$((i + 1))
done <<<"$ordered"
i=$base_idx
while IFS=$'\t' read -r _n wid; do
[ -z "$wid" ] && continue
tmux move-window -s "$wid" -t "$SESSION:$i"
i=$((i + 1))
done <<<"$ordered"
}
# Find existing window id in ai session by window name; empty if none.
find_window_id() {
tmux list-windows -t "$SESSION" -F '#{window_name}'$'\t''#{window_id}' 2>/dev/null |
_match_window_id "$1"
}
# Git prep for a single directory. Uses FETCH_HEAD cache to skip back-to-back
# fetches. Pulls automatically if clean-and-behind; prints one-line summary
# if diverged/dirty/ahead.
prep_git_single() {
local dir="$1" gitdir upstream ahead=0 behind=0 dirty=0 age fetch_stale=1 parts=()
git -C "$dir" rev-parse --is-inside-work-tree >/dev/null 2>&1 || return 0
gitdir=$(git -C "$dir" rev-parse --git-dir 2>/dev/null)
if [ -f "$gitdir/FETCH_HEAD" ]; then
age=$(($(date +%s) - $(stat -c %Y "$gitdir/FETCH_HEAD" 2>/dev/null || echo 0)))
[ "$age" -lt 600 ] && fetch_stale=0
fi
[ "$fetch_stale" -eq 1 ] && git -C "$dir" fetch --quiet 2>/dev/null || true
upstream=$(git -C "$dir" rev-parse --abbrev-ref --symbolic-full-name "@{u}" 2>/dev/null || true)
[ -z "$upstream" ] && return 0
ahead=$(git -C "$dir" rev-list --count "$upstream..HEAD" 2>/dev/null || echo 0)
behind=$(git -C "$dir" rev-list --count "HEAD..$upstream" 2>/dev/null || echo 0)
_git_blocks_sync "$dir" && dirty=1
case "$(_git_prep_action 1 "$dirty" "${ahead:-0}" "${behind:-0}")" in
pull)
echo "ai: pulling $behind commit(s) from $upstream..." >&2
git -C "$dir" pull --ff-only --quiet
;;
report)
[ "${ahead:-0}" -gt 0 ] && parts+=("↑$ahead")
[ "${behind:-0}" -gt 0 ] && parts+=("↓$behind")
[ "$dirty" -eq 1 ] && parts+=("dirty")
echo "ai: $(basename "$dir") — ${parts[*]}" >&2
;;
esac
}
# Run the project's agent-roster and turn its verdict into a launch decision.
# The decision is the only thing on stdout; warnings go to stderr so callers
# can capture one without the other.
_resolve_helper_launch() {
# Two statements on purpose: a name assigned in a `local` is not yet visible
# to a later assignment in that same `local`, so building the roster path in
# this line would read the CALLER's $dir — right only by coincidence.
local dir="$1"
local roster="$dir/.ai/scripts/agent-roster" rc decision
if [ -x "$roster" ]; then
# The roster prints the other agents it found; only its exit code matters
# here, and its stdout must not reach a --print-launch caller's output.
"$roster" "$dir" >/dev/null 2>&1
rc=$?
else
rc=absent
fi
decision="$(_helper_launch_mode "$rc")"
case "$decision" in
primary)
echo "ai: --helper found no other agent live in $(basename "$dir") — opening a normal primary session instead" >&2
;;
helper-unverified)
echo "ai: could not verify another agent is live in $(basename "$dir") — roster unavailable; opening a helper anyway" >&2
;;
esac
echo "$decision"
}
# ---------- modes ----------
attach_mode() {
if ! tmux has-session -t "$SESSION" 2>/dev/null; then
echo "ai: no '$SESSION' session to attach to" >&2
exit 1
fi
sort_windows
attach_session
}
# Open a single project (or focus existing window).
single_mode() {
local arg="$1" dir name wid existing
dir="$(cd "$arg" 2>/dev/null && pwd)" || {
echo "ai: cannot access '$arg'" >&2
return 1
}
if [ ! -f "$dir/.ai/protocols.org" ]; then
echo "ai: $dir has no .ai/protocols.org — not a Claude-template project" >&2
return 1
fi
name="$(basename "$dir")"
# Window already exists? Focus it, skip git prep (claude is running in there).
if tmux has-session -t "$SESSION" 2>/dev/null; then
existing=$(find_window_id "$name")
if [ -n "$existing" ]; then
tmux select-window -t "$existing"
attach_session
return 0
fi
fi
prep_git_single "$dir"
# Create session with first window, or add a new window.
if tmux has-session -t "$SESSION" 2>/dev/null; then
wid=$(create_window "$dir" "$name")
else
local instructions
wid=$(tmux new-session -d -s "$SESSION" -n "$name" -c "$dir" -P -F '#{window_id}')
instructions=$(build_instructions "$name")
tmux send-keys -t "$wid" "${LAUNCH_PREFIX}$AGENT_CMD \"$instructions\"" Enter
fi
sort_windows
tmux select-window -t "$wid"
attach_session
}
# Open a helper session: a second agent in a project that already has a live
# one. Two deliberate differences from single_mode. It never focuses an
# existing window — a second session is the entire point, and focusing the
# primary's window is the one outcome that can't be what was asked for. And it
# never runs git prep, because every pull belongs to the primary under the
# helper contract.
helper_mode() {
local arg="$1" dir name id wid wname decision instructions
dir="$(cd "$arg" 2>/dev/null && pwd)" || {
echo "ai: cannot access '$arg'" >&2
return 1
}
if [ ! -f "$dir/.ai/protocols.org" ]; then
echo "ai: $dir has no .ai/protocols.org — not an agent-template project" >&2
return 1
fi
name="$(basename "$dir")"
# Nobody else is here, so there is nothing to be a helper to. Fall through to
# the normal launch rather than opening a crippled session.
decision="$(_resolve_helper_launch "$dir")"
if [ "$decision" = primary ]; then
single_mode "$arg"
return $?
fi
id="$(_resolve_helper_id "$dir")"
wname="$name:$id"
instructions=$(build_helper_instructions "$name")
if tmux has-session -t "$SESSION" 2>/dev/null; then
wid=$(tmux new-window -a -t "$SESSION:{end}" -n "$wname" -c "$dir" -P -F '#{window_id}')
sleep 0.1
else
wid=$(tmux new-session -d -s "$SESSION" -n "$wname" -c "$dir" -P -F '#{window_id}')
fi
# The id rides in the launched process's environment, which is what
# session-context-path reads to resolve .ai/session-context.d/<id>.org.
tmux send-keys -t "$wid" \
"${LAUNCH_PREFIX}AI_AGENT_ID=$id AI_HELPER=1 $AGENT_CMD \"$instructions\"" Enter
sort_windows
tmux select-window -t "$wid"
attach_session
}
# Multi-select via fzf (the original aix flow).
multi_mode() {
local filtered=() selections first_wid=""
if tmux has-session -t "$SESSION" 2>/dev/null; then
# Add to existing session — filter out projects already open.
local existing
existing=$(tmux list-windows -t "$SESSION" -F '#{window_name}')
build_candidates
for c in "${candidates[@]}"; do
local n
n="$(basename "${c/#\~/$HOME}")"
if ! echo "$existing" | grep -qxF "$n"; then
filtered+=("$c")
fi
done
if [ ${#filtered[@]} -eq 0 ]; then
echo "All projects already have windows open."
sort_windows
attach_session
return 0
fi
candidates=("${filtered[@]}")
else
build_candidates
fi
echo "Fetching remotes..." >&2
fetch_candidates
annotate_candidates
# One-line summary: total / clean / changed
local _total=${#candidates[@]} _clean _changed
_clean=$(printf '%s\n' "${candidates[@]}" | grep -c ' (✓)$' || true)
_changed=$((_total - _clean))
echo "Fetched $_total projects: $_clean clean, $_changed with changes" >&2
selections=$(printf '%s\n' "${candidates[@]}" | fzf --multi --height=70% --reverse) || true
[ -z "$selections" ] && return 0
read_selections "$selections"
if ! tmux has-session -t "$SESSION" 2>/dev/null; then
# Create session with first selection
local first="${selected[0]}"
local dir name
dir="${first/#\~/$HOME}"
name="$(basename "$dir")"
auto_pull_if_clean "$dir"
local instructions
first_wid=$(tmux new-session -d -s "$SESSION" -n "$name" -c "$dir" -P -F '#{window_id}')
instructions=$(build_instructions "$name")
tmux send-keys -t "$first_wid" "${LAUNCH_PREFIX}$AGENT_CMD \"$instructions\"" Enter
for entry in "${selected[@]:1}"; do
dir="${entry/#\~/$HOME}"
name="$(basename "$dir")"
auto_pull_if_clean "$dir"
create_window "$dir" "$name" >/dev/null
done
else
# Add windows to existing session
for entry in "${selected[@]}"; do
local dir name wid
dir="${entry/#\~/$HOME}"
name="$(basename "$dir")"
auto_pull_if_clean "$dir"
wid=$(create_window "$dir" "$name")
[ -z "$first_wid" ] && first_wid="$wid"
done
fi
sort_windows
[ -n "$first_wid" ] && tmux select-window -t "$first_wid"
attach_session
}
# Print the launch command a real run would send to the pane, then exit.
# Exists for the launcher's bats tests: exercises runtime resolution and the
# opening line with no tmux or fzf involved.
print_launch_mode() {
local arg="$1" dir name
dir="$(cd "$arg" 2>/dev/null && pwd)" || {
echo "ai: cannot access '$arg'" >&2
exit 1
}
if [ ! -f "$dir/.ai/protocols.org" ]; then
echo "ai: $dir has no .ai/protocols.org — not an agent-template project" >&2
exit 1
fi
name="$(basename "$dir")"
# The roster runs here too, so the printed line reflects the decision a real
# run would make — including the downgrade to a primary launch.
if [ -n "$HELPER_MODE" ] && [ "$(_resolve_helper_launch "$dir")" != primary ]; then
printf 'AI_AGENT_ID=%s AI_HELPER=1 %s "%s"\n' \
"$(_resolve_helper_id "$dir")" "$AGENT_CMD" "$(build_helper_instructions "$name")"
exit 0
fi
printf '%s "%s"\n' "$AGENT_CMD" "$(build_instructions "$name")"
exit 0
}
# ---------- dispatch ----------
# Argument parsing + mode dispatch. Wrapped so the file can be sourced (by the
# launcher's bats tests) to exercise individual functions without running a
# real launch. When executed as a program, BASH_SOURCE[0] equals $0 and the
# dispatch runs exactly as before; when sourced, it's skipped.
main() {
print_launch=""
HELPER_MODE=""
runtime_explicit="${AI_RUNTIME:+1}"
while [ $# -gt 0 ]; do
case "$1" in
-h | --help)
usage
;;
--helper)
HELPER_MODE=1
shift
;;
--runtime)
[ -z "${2:-}" ] && {
echo "ai: --runtime needs a value — valid runtimes: claude, codex, local" >&2
exit 2
}
RUNTIME="$2"
runtime_explicit=1
shift 2
;;
--runtime=*)
RUNTIME="${1#--runtime=}"
runtime_explicit=1
shift
;;
--print-launch)
print_launch=1
shift
;;
--print-runtimes)
build_runtime_choices
exit 0
;;
*)
break
;;
esac
done
resolve_agent_cmd
# A helper is always scoped to one named project. There is no roster to check
# and no primary to help without one, so this can't fall back to the picker.
if [ -n "$HELPER_MODE" ] && [ -z "${1:-}" ]; then
echo "ai: --helper needs a project directory" >&2
exit 2
fi
if [ -n "$print_launch" ]; then
[ $# -eq 0 ] && {
echo "ai: --print-launch needs a project directory" >&2
exit 2
}
print_launch_mode "$1"
fi
case "${1:-}" in
--attach)
check_deps
attach_mode
;;
"")
# Bare `ai`: pick the agent first (skipped when --runtime or AI_RUNTIME
# already chose), then the familiar project multi-select.
if [ -z "$runtime_explicit" ]; then
pick_runtime || exit 0
fi
check_deps
multi_mode
;;
*)
check_deps
for arg in "$@"; do
if [ -n "$HELPER_MODE" ]; then
helper_mode "$arg"
else
single_mode "$arg"
fi
done
;;
esac
}
if [ "${BASH_SOURCE[0]}" = "${0}" ]; then
main "$@"
fi
|