-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.sh
More file actions
executable file
·983 lines (888 loc) · 37.8 KB
/
Copy pathsetup.sh
File metadata and controls
executable file
·983 lines (888 loc) · 37.8 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
#!/usr/bin/env bash
#
# Afterwords — local voice-cloning TTS server
#
# Zero-shot voice cloning via Qwen3-TTS on Apple Silicon.
# Works standalone as an HTTP API, or integrates with Claude Code
# for automatic text-to-speech on every response.
#
# Requirements: Apple Silicon Mac (M1+), 16 GB+ RAM (32 GB recommended), Python 3.11+
# Usage: bash setup.sh # full setup (detects Claude Code)
# bash setup.sh --server-only # server + voices only, no hooks
#
set -euo pipefail
# ── Flags ─────────────────────────────────────────────────────────
SERVER_ONLY=false
for arg in "$@"; do
case "$arg" in
--server-only) SERVER_ONLY=true ;;
esac
done
# ── Colours & output helpers ────────────────────────────────────────
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[0;33m'
CYAN='\033[0;36m'; DIM='\033[2m'; BOLD='\033[1m'; NC='\033[0m'
info() { echo -e " ${CYAN}▸${NC} $*"; }
ok() { echo -e " ${GREEN}✓${NC} $*"; }
warn() { echo -e " ${YELLOW}⚠${NC} $*"; }
fail() { echo -e " ${RED}✗${NC} $*"; exit 1; }
ask() { echo -en " ${BOLD}$*${NC} "; }
step() { echo; echo -e "${BOLD}$1${NC} ${DIM}$2${NC}"; }
rule() { echo -e "${DIM} ─────────────────────────────────────────${NC}"; }
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"
# Temp file cleanup on any exit
TMPFILES=()
cleanup() { [ ${#TMPFILES[@]} -gt 0 ] && rm -rf "${TMPFILES[@]}" 2>/dev/null; true; }
trap cleanup EXIT
# ── Timing ─────────────────────────────────────────────────────────
_T0=$(date +%s)
# ── Step 0: Preflight checks ──────────────────────────────────────
echo
echo -e " ${BOLD}afterwords${NC} ${DIM}— local voice-cloning TTS server${NC}"
rule
# Apple Silicon check (allow Rosetta — MLX still works via arm64 Python)
ARCH=$(sysctl -n machdep.cpu.brand_string 2>/dev/null || uname -m)
if [[ "$ARCH" != *"Apple"* && "$(uname -m)" != "arm64" ]]; then
fail "This requires Apple Silicon (M1/M2/M3/M4). Detected: ${ARCH}"
fi
ok "Apple Silicon detected"
# RAM check
RAM_BYTES=$(sysctl -n hw.memsize 2>/dev/null || echo 0)
if ! [[ "$RAM_BYTES" =~ ^[0-9]+$ ]]; then
warn "Could not detect RAM size. Proceeding anyway."
RAM_GB="?"
else
RAM_GB=$((RAM_BYTES / 1073741824))
if [[ "$RAM_GB" -lt 16 ]]; then
fail "Need 16 GB+ RAM. Detected: ${RAM_GB} GB"
fi
if [[ "$RAM_GB" -lt 32 ]]; then
warn "${RAM_GB} GB RAM — 32 GB recommended for best results"
fi
fi
ok "${RAM_GB} GB RAM"
# Python check (need 3.11+)
if ! command -v python3 &>/dev/null; then
fail "Python 3 not found. Install: brew install python"
fi
PY_VER=$(python3 -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')
PY_OK=$(python3 -c 'import sys; print(1 if sys.version_info >= (3, 11) else 0)')
if [[ "$PY_OK" != "1" ]]; then
fail "Python 3.11+ required. Detected: ${PY_VER}. Upgrade: brew install python"
fi
ok "Python ${PY_VER}"
# ffmpeg check
if ! command -v ffmpeg &>/dev/null; then
warn "ffmpeg not found — installing via Homebrew..."
command -v brew &>/dev/null || fail "ffmpeg required. Install Homebrew first: https://brew.sh"
brew install ffmpeg
fi
ok "ffmpeg"
# jq check
if ! command -v jq &>/dev/null; then
warn "jq not found — installing via Homebrew..."
command -v brew &>/dev/null || fail "jq required. Install Homebrew first: https://brew.sh"
brew install jq
fi
ok "jq"
# yt-dlp check
if ! command -v yt-dlp &>/dev/null; then
if command -v brew &>/dev/null; then
warn "yt-dlp not found — installing via Homebrew..."
brew install yt-dlp
else
warn "yt-dlp not found — installing via pip..."
pip3 install --user yt-dlp 2>/dev/null || pip3 install yt-dlp
fi
fi
ok "yt-dlp"
# lame check (optional — for MP3 archiving)
if ! command -v lame &>/dev/null; then
if command -v brew &>/dev/null; then
warn "lame not found — installing via Homebrew (for MP3 archiving)..."
brew install lame
else
warn "lame not found. Spoken responses won't be archived as MP3."
fi
fi
# ── Claude Code detection ────────────────────────────────────────
HAS_CLAUDE=false
if $SERVER_ONLY; then
info "Server-only mode — skipping Claude Code integration"
elif command -v claude &>/dev/null; then
HAS_CLAUDE=true
ok "Claude Code detected"
else
echo
echo -e " ${BOLD}Claude Code not found.${NC}"
echo -e " Afterwords works best with Claude Code — it speaks every response."
echo -e " Without it, you get a standalone TTS API at localhost:7860."
echo
ask "Install Claude Code? [Y/n]:"
read -r INSTALL_CLAUDE
INSTALL_CLAUDE="${INSTALL_CLAUDE:-Y}"
if [[ "$INSTALL_CLAUDE" =~ ^[Yy] ]]; then
# Need Node.js / npm
if ! command -v npm &>/dev/null; then
if command -v brew &>/dev/null; then
info "Installing Node.js via Homebrew..."
brew install node
else
warn "npm not found and Homebrew not available."
warn "Install Node.js from https://nodejs.org then re-run setup."
info "Continuing in server-only mode."
fi
fi
if command -v npm &>/dev/null; then
info "Installing Claude Code..."
if npm install -g @anthropic-ai/claude-code 2>&1 | tail -3; then
if command -v claude &>/dev/null; then
HAS_CLAUDE=true
ok "Claude Code installed"
else
warn "Claude Code installed but 'claude' not on PATH."
warn "You may need to restart your terminal. Continuing in server-only mode."
fi
else
warn "Claude Code installation failed. Continuing in server-only mode."
fi
fi
else
info "Skipping Claude Code — setting up server only"
fi
fi
if $HAS_CLAUDE; then
TOTAL_STEPS=5
else
TOTAL_STEPS=4
fi
STEP=0
next_step() { STEP=$((STEP + 1)); step "${STEP}/${TOTAL_STEPS}" "$1"; }
next_step "Python environment"
if [ -d ".venv" ]; then
# Verify venv is functional
if ! ".venv/bin/python3" -c "pass" 2>/dev/null; then
warn "Existing .venv is broken — rebuilding..."
rm -rf .venv
python3 -m venv .venv
ok "Rebuilt .venv"
else
ok ".venv exists and works"
fi
else
python3 -m venv .venv
ok "Created .venv"
fi
source .venv/bin/activate
pip install --quiet --upgrade pip
pip install --quiet -r requirements.txt
if ! $SERVER_ONLY; then
pip install --quiet -r requirements-clone.txt
fi
ok "Python packages installed"
echo
next_step "Voice source"
mkdir -p voices
if [ -z "$(find voices -maxdepth 1 -name '*-ref.wav' -print -quit 2>/dev/null)" ]; then
info "No voice profiles found. Let's create one."
echo
echo -e " You need a ${BOLD}YouTube URL${NC} with someone speaking."
echo -e " The setup will extract a 15-second clip for voice cloning."
echo -e " ${YELLOW}Tips:${NC} Choose a clip with clear speech, minimal background noise,"
echo -e " and one speaker. Interviews and monologues work best."
echo
ask "YouTube URL:"
read -r YT_URL
[ -z "$YT_URL" ] && fail "No URL provided"
TMP_DL_DIR=$(mktemp -d)
TMP_SRC="$TMP_DL_DIR/source.wav"
TMPFILES+=("$TMP_DL_DIR")
info "Downloading audio..."
if ! yt-dlp -x --audio-format wav -o "$TMP_DL_DIR/source.%(ext)s" "$YT_URL" 2>&1 | tail -5; then
fail "Download failed. Check the URL and try again."
fi
# yt-dlp may leave intermediate files; find the final wav
[ -f "$TMP_SRC" ] || TMP_SRC=$(find "$TMP_DL_DIR" -name '*.wav' -print -quit)
[ -f "$TMP_SRC" ] || fail "Download produced no audio file. Check the URL."
DURATION=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "$TMP_SRC" 2>/dev/null | cut -d. -f1)
[[ "$DURATION" =~ ^[0-9]+$ ]] || DURATION="unknown"
if [[ "$DURATION" == "unknown" ]]; then
info "Clip duration: unknown"
else
info "Clip duration: ${DURATION}s"
fi
echo
echo -e " We need a ${BOLD}15-second${NC} segment with clear speech from one person."
ask "Start time in seconds (default: 0):"
read -r START_S
START_S="${START_S:-0}"
# Sanitise: must be a number
[[ "$START_S" =~ ^[0-9]+$ ]] || fail "Start time must be a number"
ask "Voice name (letters, numbers, hyphens only — e.g., galadriel, sam):"
read -r VOICE_NAME
VOICE_NAME="${VOICE_NAME:-default}"
# Sanitise: alphanumeric and hyphens only, no path traversal
VOICE_NAME=$(echo "$VOICE_NAME" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9-]//g')
[ -z "$VOICE_NAME" ] && VOICE_NAME="voice"
TMP_SEG="/tmp/voice-setup-segment-$$.wav"
TMPFILES+=("$TMP_SEG")
info "Extracting reference (${START_S}s → $((START_S+15))s)..."
ffmpeg -y -i "$TMP_SRC" -ss "$START_S" -t 15 -ar 24000 -ac 1 "$TMP_SEG" 2>/dev/null
info "Denoising..."
python3 - "$TMP_SEG" "voices/${VOICE_NAME}-ref.wav" <<'PYEOF'
import sys, soundfile as sf, noisereduce as nr, numpy as np
data, sr = sf.read(sys.argv[1])
reduced = nr.reduce_noise(y=data, sr=sr, stationary=True, prop_decrease=0.7)
peak = np.max(np.abs(reduced))
if peak > 0:
reduced = reduced * (0.9 / peak)
sf.write(sys.argv[2], reduced, sr, subtype="PCM_16")
print(f" {len(reduced)/sr:.1f}s saved")
PYEOF
ok "Reference audio ready"
info "Transcribing with Whisper..."
REF_TEXT=$(python3 - "voices/${VOICE_NAME}-ref.wav" <<'PYEOF'
import sys
from faster_whisper import WhisperModel
model = WhisperModel("base.en", compute_type="int8")
segments, _ = model.transcribe(sys.argv[1])
print(" ".join(seg.text.strip() for seg in segments))
PYEOF
) || fail "Transcription failed. Is faster-whisper installed?"
echo
echo -e " ${BOLD}Transcript:${NC}"
echo -e " ${CYAN}${REF_TEXT}${NC}"
echo
echo -e " ${YELLOW}Important:${NC} Verify this matches exactly what you hear."
ask "Press Enter to accept, or type a corrected transcript:"
read -r CORRECTED
[ -n "$CORRECTED" ] && REF_TEXT="$CORRECTED"
# Save profile using Python for safe JSON serialisation (no shell interpolation)
python3 - "$VOICE_NAME" "$YT_URL" "$REF_TEXT" "$START_S" <<'PYEOF'
import json, sys
name, url, text, start = sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4])
with open(f"voices/{name}.json", "w") as f:
json.dump({"name": name, "source_url": url, "reference_audio": f"{name}-ref.wav",
"reference_text": text, "segment_start_s": start}, f, indent=2)
PYEOF
ok "Voice profile saved: voices/${VOICE_NAME}.json"
else
ok "Voice profiles found:"
for f in voices/*.json; do
[ -f "$f" ] || continue
name=$(python3 -c "import json,sys; f=open(sys.argv[1]); print(json.load(f)['name']); f.close()" "$f" 2>/dev/null || basename "$f" .json)
echo -e " ${CYAN}${name}${NC}"
done
fi
echo
next_step "Server check"
VOICE_FILES=$(ls voices/*-ref.wav 2>/dev/null | wc -l | tr -d ' ')
ok "${VOICE_FILES} voice file(s) in voices/"
if grep -q "^VOICES = {" server.py 2>/dev/null; then
ok "server.py has multi-voice support"
else
warn "server.py may need updating for multi-voice support."
fi
echo
if ! $SERVER_ONLY && { $HAS_CLAUDE || command -v gemini &>/dev/null || command -v agy &>/dev/null; }; then
next_step "Claude & CLI hooks"
HOOKS_DIR="$HOME/.claude/hooks"
mkdir -p "$HOOKS_DIR"
# Back up existing hooks if present
for hookfile in strip-markdown.py chunk-text.py tts-hook.sh tts-worker.sh gemini-tts-hook.sh agy-tts-hook.sh agy-session-hook.py; do
if [ -f "$HOOKS_DIR/$hookfile" ]; then
cp "$HOOKS_DIR/$hookfile" "$HOOKS_DIR/$hookfile.bak"
fi
done
# Strip-markdown helper
cp "$SCRIPT_DIR/strip_markdown.py" "$HOOKS_DIR/strip-markdown.py"
# Chunk-text helper (sentence splitter for chunked TTS)
cp "$SCRIPT_DIR/chunk_text.py" "$HOOKS_DIR/chunk-text.py"
# Copy CLI hook helper files if present
[ -f "$SCRIPT_DIR/agy_session_hook.py" ] && cp "$SCRIPT_DIR/agy_session_hook.py" "$HOOKS_DIR/agy-session-hook.py"
[ -f "$SCRIPT_DIR/.claude/hooks/gemini-tts-hook.sh" ] && cp "$SCRIPT_DIR/.claude/hooks/gemini-tts-hook.sh" "$HOOKS_DIR/gemini-tts-hook.sh" && chmod +x "$HOOKS_DIR/gemini-tts-hook.sh"
[ -f "$SCRIPT_DIR/.claude/hooks/agy-tts-hook.sh" ] && cp "$SCRIPT_DIR/.claude/hooks/agy-tts-hook.sh" "$HOOKS_DIR/agy-tts-hook.sh" && chmod +x "$HOOKS_DIR/agy-tts-hook.sh"
# TTS hook (fires on Stop event)
cat > "$HOOKS_DIR/tts-hook.sh" <<'HOOKEOF'
#!/usr/bin/env bash
# Queue Claude's last response for TTS.
QUEUEDIR="/tmp/claude-tts-queue"
WORKER_PID="/tmp/claude-tts-worker.pid"
WORKER="$HOME/.claude/hooks/tts-worker.sh"
# Read stdin once (hook payload JSON)
INPUT=$(cat)
TEXT=$(printf '%s' "$INPUT" | jq -r '.last_assistant_message // empty' 2>/dev/null \
| python3 "$HOME/.claude/hooks/strip-markdown.py" 2>/dev/null)
[ -z "$TEXT" ] && exit 0
# Agent type (empty for main conversation, e.g. "clara-oswald" for subagents)
AGENT=$(printf '%s' "$INPUT" | jq -r '.agent_type // empty' 2>/dev/null)
# Skip built-in subagent types (their output goes to the parent, not the user)
case "$AGENT" in
Explore|Plan|general-purpose) exit 0 ;;
esac
if [ -L "$QUEUEDIR" ]; then
echo "afterwords: $QUEUEDIR is a symlink — refusing to use it" >&2
exit 1
fi
mkdir -p "$QUEUEDIR"
chmod 700 "$QUEUEDIR" 2>/dev/null || true
if [ ! -d "$QUEUEDIR" ] || [ "$(stat -f%u "$QUEUEDIR" 2>/dev/null)" != "$(id -u)" ]; then
echo "afterwords: $QUEUEDIR is not a directory we own — refusing to use it" >&2
exit 1
fi
ITEM="${QUEUEDIR}/$(date +%s)-${RANDOM}.json"
ITEM_TMP="${ITEM}.tmp"
python3 -c "
import json, sys
print(json.dumps({'project_dir': sys.argv[1], 'agent': sys.argv[2], 'text': sys.argv[3]}))
" "$PWD" "$AGENT" "$TEXT" > "$ITEM_TMP" && mv "$ITEM_TMP" "$ITEM"
if [ -f "$WORKER_PID" ]; then
EXISTING=$(cat "$WORKER_PID" 2>/dev/null)
if [ -n "$EXISTING" ] && kill -0 "$EXISTING" 2>/dev/null; then
exit 0
fi
rm -f "$WORKER_PID"
fi
nohup bash "$WORKER" >/dev/null 2>&1 &
HOOKEOF
chmod +x "$HOOKS_DIR/tts-hook.sh"
# TTS worker (processes queue)
cat > "$HOOKS_DIR/tts-worker.sh" <<'WORKEREOF'
#!/usr/bin/env bash
set -uo pipefail
QUEUEDIR="/tmp/claude-tts-queue"
PIDFILE="/tmp/claude-tts-worker.pid"
LOCKDIR="/tmp/claude-tts-worker.lock"
TTS_URL="http://127.0.0.1:7860/synthesize"
ARCHIVE_DIR="$HOME/.claude/tts-archive"
MAX_QUEUE=10
mkdir -p "$ARCHIVE_DIR"
PLAY_LOCK="/tmp/afterwords-play.lock"
PLAY_PID="/tmp/afterwords-play.pid"
MUTE_FILE="/tmp/afterwords-muted"
acquire_play_lock() {
local w=0
while ! mkdir "$PLAY_LOCK" 2>/dev/null; do
local h; h=$(cat "$PLAY_PID" 2>/dev/null)
if [ -z "$h" ]; then sleep 0.05; h=$(cat "$PLAY_PID" 2>/dev/null); fi
if [ -z "$h" ] || ! kill -0 "$h" 2>/dev/null; then
rm -rf "$PLAY_LOCK" "$PLAY_PID"
else
sleep 0.3; w=$((w+1)); [ "$w" -gt 200 ] && return 1
fi
done
echo $$ > "$PLAY_PID"
}
release_play_lock() { rm -f "$PLAY_PID"; rm -rf "$PLAY_LOCK"; }
if ! mkdir "$LOCKDIR" 2>/dev/null; then
if [ -f "$PIDFILE" ]; then
HOLDER=$(cat "$PIDFILE" 2>/dev/null)
if [ -n "$HOLDER" ] && kill -0 "$HOLDER" 2>/dev/null; then
exit 0
fi
rm -rf "$LOCKDIR"
mkdir "$LOCKDIR" 2>/dev/null || exit 0
else
exit 0
fi
fi
echo $$ > "$PIDFILE"
trap 'rm -f "$PIDFILE"; rm -rf "$LOCKDIR"' EXIT
if [ -L "$QUEUEDIR" ]; then
echo "afterwords: $QUEUEDIR is a symlink — refusing to use it" >&2
exit 1
fi
mkdir -p "$QUEUEDIR"
chmod 700 "$QUEUEDIR" 2>/dev/null || true
if [ ! -d "$QUEUEDIR" ] || [ "$(stat -f%u "$QUEUEDIR" 2>/dev/null)" != "$(id -u)" ]; then
echo "afterwords: $QUEUEDIR is not a directory we own — refusing to use it" >&2
exit 1
fi
while true; do
# Prune excess items (keep newest MAX_QUEUE).
COUNT=0
while IFS= read -r EXCESS; do
COUNT=$((COUNT + 1))
[ "$COUNT" -gt "$MAX_QUEUE" ] && rm -f "$EXCESS"
done < <(ls -1t "$QUEUEDIR"/*.json 2>/dev/null)
# Claim oldest unclaimed item atomically via mv.
ITEM=""
while IFS= read -r CANDIDATE; do
CLAIMED="${CANDIDATE%.json}.claimed"
if mv "$CANDIDATE" "$CLAIMED" 2>/dev/null; then
ITEM="$CLAIMED"
break
fi
done < <(ls -1t "$QUEUEDIR"/*.json 2>/dev/null | tail -r 2>/dev/null || ls -1 "$QUEUEDIR"/*.json 2>/dev/null | sort)
[ -z "$ITEM" ] && break
ITEM_EVAL=$(python3 -c "
import json, sys, shlex
d = json.load(open(sys.argv[1]))
print('PROJECT_DIR=' + shlex.quote(d.get('project_dir','')))
print('AGENT=' + shlex.quote(d.get('agent','')))
print('LINE=' + shlex.quote(d.get('text','')))
" "$ITEM" 2>/dev/null) || { rm -f "$ITEM"; continue; }
eval "$ITEM_EVAL"
rm -f "$ITEM"
[ -z "${LINE:-}" ] && continue
STAMP=$(date +%Y%m%d-%H%M%S)-$$-$RANDOM
# Resolve voice: .afterwords mapping → .afterwords single → server default
VOICE=""
AW_FILE=""
if [ -n "$PROJECT_DIR" ] && [ -f "$PROJECT_DIR/.afterwords" ]; then
AW_FILE="$PROJECT_DIR/.afterwords"
elif [ -f "$HOME/.afterwords" ]; then
AW_FILE="$HOME/.afterwords"
fi
if [ -n "$AW_FILE" ]; then
if grep -q ':' "$AW_FILE" 2>/dev/null; then
# Mapping mode. Split on the final colon so keys may contain colons.
VOICE=$(awk -v agent="$AGENT" '
function trim(s) { gsub(/^[[:space:]]+|[[:space:]]+$/, "", s); return s }
/^[[:space:]]*#/ || /^[[:space:]]*$/ { next }
{
pos = 0
for (i = 1; i <= length($0); i++) {
if (substr($0, i, 1) == ":") pos = i
}
if (!pos) next
key = trim(substr($0, 1, pos - 1))
val = trim(substr($0, pos + 1))
if (agent != "" && key == agent) { print val; found = 1; exit }
if (key == "default" && fallback == "") fallback = val
}
END { if (!found && fallback != "") print fallback }
' "$AW_FILE" 2>/dev/null)
else
# Legacy mode: first non-empty line is the voice name
VOICE=$(head -1 "$AW_FILE" 2>/dev/null | tr -d '[:space:]')
fi
fi
if [ -z "$VOICE" ]; then
VOICE=$(curl -s --max-time 2 "${TTS_URL%/synthesize}/health" 2>/dev/null \
| python3 -c "import sys,json; print(json.load(sys.stdin).get('default_voice',''))" 2>/dev/null || true)
fi
VOICE_PARAM=""
if [ -n "$VOICE" ]; then
VOICE_ENC=$(python3 -c "import sys,urllib.parse; print(urllib.parse.quote(sys.argv[1]))" "$VOICE" 2>/dev/null) || VOICE_ENC="$VOICE"
VOICE_PARAM="&voice=${VOICE_ENC}"
fi
# Archive: full response text sidecar (written once; chunk audio archived per-chunk below).
ARCHIVE_BASE="$ARCHIVE_DIR/${VOICE:-default}-${STAMP}"
printf '%s\n' "$LINE" > "${ARCHIVE_BASE}.txt"
acquire_play_lock || continue
# Split into sentence-boundary chunks and pipeline: synth-N → play-N → synth-N+1.
# Latency-to-first-audio drops from ~30s (full blob) to ~2s (first chunk).
CHUNK_SCRIPT="$HOME/.claude/hooks/chunk-text.py"
CHUNK_DIR="/tmp/claude-tts-chunks-$$"
mkdir -p "$CHUNK_DIR"
# Collect chunks into numbered text files (Bash 3.2-compatible; no mapfile).
NCHUNKS=0
while IFS= read -r CHUNK; do
[ -z "$CHUNK" ] && continue
NCHUNKS=$((NCHUNKS + 1))
printf '%s' "$CHUNK" > "${CHUNK_DIR}/${NCHUNKS}.txt"
done < <([ -f "$CHUNK_SCRIPT" ] && python3 "$CHUNK_SCRIPT" <<< "$LINE" 2>/dev/null \
|| printf '%s\n' "$LINE")
PREV_WAV=""
SYNTH_PID=""
CHUNK_I=1
while [ "$CHUNK_I" -le "$NCHUNKS" ]; do
CHUNK=$(cat "${CHUNK_DIR}/${CHUNK_I}.txt")
CURR_WAV="${CHUNK_DIR}/${CHUNK_I}.wav"
ENC=$(python3 -c "import sys,urllib.parse; print(urllib.parse.quote(sys.argv[1]))" "$CHUNK" 2>/dev/null) || { CHUNK_I=$((CHUNK_I+1)); continue; }
# Wait for previous synth to finish (so PREV_WAV is fully written).
[ -n "$SYNTH_PID" ] && { wait "$SYNTH_PID"; SYNTH_PID=""; }
# Start current synth in background BEFORE playing previous chunk —
# this is the overlap: synth(N+1) runs while afplay plays chunk(N).
curl -s --max-time 60 "${TTS_URL}?text=${ENC}${VOICE_PARAM}" -o "$CURR_WAV" 2>/dev/null &
SYNTH_PID=$!
if [ -n "$PREV_WAV" ] && [ -f "$PREV_WAV" ]; then
FILESIZE=$(stat -f%z "$PREV_WAV" 2>/dev/null || echo 0)
if [ "$FILESIZE" -gt 1000 ]; then
TRIMMED="${PREV_WAV%.wav}.trimmed.wav"
ffmpeg -y -ss 0.1 -i "$PREV_WAV" -c copy "$TRIMMED" 2>/dev/null \
&& mv "$TRIMMED" "$PREV_WAV" || rm -f "$TRIMMED"
lame --quiet -V 2 "$PREV_WAV" "${ARCHIVE_BASE}-c$((CHUNK_I-1)).mp3" 2>/dev/null || true
[ -f "$MUTE_FILE" ] || afplay "$PREV_WAV" 2>/dev/null
fi
rm -f "$PREV_WAV"
fi
PREV_WAV="$CURR_WAV"
CHUNK_I=$((CHUNK_I + 1))
done
# Play the last chunk.
[ -n "$SYNTH_PID" ] && wait "$SYNTH_PID"
if [ -n "$PREV_WAV" ] && [ -f "$PREV_WAV" ]; then
FILESIZE=$(stat -f%z "$PREV_WAV" 2>/dev/null || echo 0)
if [ "$FILESIZE" -gt 1000 ]; then
TRIMMED="${PREV_WAV%.wav}.trimmed.wav"
ffmpeg -y -ss 0.1 -i "$PREV_WAV" -c copy "$TRIMMED" 2>/dev/null \
&& mv "$TRIMMED" "$PREV_WAV" || rm -f "$TRIMMED"
lame --quiet -V 2 "$PREV_WAV" "${ARCHIVE_BASE}-c${NCHUNKS}.mp3" 2>/dev/null || true
[ -f "$MUTE_FILE" ] || afplay "$PREV_WAV" 2>/dev/null
fi
rm -f "$PREV_WAV"
fi
release_play_lock
rm -rf "$CHUNK_DIR"
done
WORKEREOF
chmod +x "$HOOKS_DIR/tts-worker.sh"
ok "Hook scripts installed (backups saved as *.bak)"
# Wire into Claude Code settings
SETTINGS="$HOME/.claude/settings.json"
mkdir -p "$HOME/.claude"
HOOK_CMD="bash ~/.claude/hooks/tts-hook.sh"
HOOK_ENTRY="{\"type\": \"command\", \"command\": \"$HOOK_CMD\", \"timeout\": 120, \"async\": true}"
HOOK_GROUP="{\"hooks\": [$HOOK_ENTRY]}"
# Register the TTS hook on BOTH Stop (main conversation) and SubagentStop
# (subagent completion) so per-agent .afterwords mappings actually fire.
register_hook_event() {
local EVT="$1"
if jq -e ".hooks.${EVT}[]?.hooks[]? | select(.command == \"$HOOK_CMD\")" "$SETTINGS" &>/dev/null; then
ok "TTS hook already configured for ${EVT}"
elif jq -e ".hooks.${EVT} | type == \"array\" and length > 0 and .[0].hooks" "$SETTINGS" &>/dev/null; then
info "Appending TTS hook to existing ${EVT} hooks..."
TMPF=$(mktemp)
TMPFILES+=("$TMPF")
jq ".hooks.${EVT}[0].hooks += [$HOOK_ENTRY]" "$SETTINGS" > "$TMPF" \
&& mv "$TMPF" "$SETTINGS"
ok "TTS hook appended to existing ${EVT} hooks"
elif jq -e '.hooks' "$SETTINGS" &>/dev/null; then
info "Adding ${EVT} hook group to settings.json..."
TMPF=$(mktemp)
TMPFILES+=("$TMPF")
jq ".hooks.${EVT} = [$HOOK_GROUP]" "$SETTINGS" > "$TMPF" \
&& mv "$TMPF" "$SETTINGS"
ok "${EVT} hook added"
else
info "Adding hooks to settings.json..."
TMPF=$(mktemp)
TMPFILES+=("$TMPF")
jq ". + {\"hooks\": {\"${EVT}\": [$HOOK_GROUP]}}" "$SETTINGS" > "$TMPF" \
&& mv "$TMPF" "$SETTINGS"
ok "${EVT} hook added"
fi
}
if [ -f "$SETTINGS" ]; then
register_hook_event Stop
register_hook_event SubagentStop
else
info "Creating settings.json with Stop + SubagentStop hooks..."
cat > "$SETTINGS" <<SETTINGSEOF
{
"hooks": {
"Stop": [{
"hooks": [{
"type": "command",
"command": "$HOOK_CMD",
"timeout": 120,
"async": true
}]
}],
"SubagentStop": [{
"hooks": [{
"type": "command",
"command": "$HOOK_CMD",
"timeout": 120,
"async": true
}]
}]
}
}
SETTINGSEOF
ok "settings.json created"
fi
echo
fi # end HAS_CLAUDE hooks block
next_step "Auto-start service"
PLIST_NAME="com.afterwords.tts-server"
PLIST_PATH="$HOME/Library/LaunchAgents/${PLIST_NAME}.plist"
VENV_PYTHON="${SCRIPT_DIR}/.venv/bin/python3"
AFTERWORDS_SERVER_CONFIG="$HOME/.afterwords-server"
{
cat <<PLIST_HEAD
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>${PLIST_NAME}</string>
<key>ProgramArguments</key>
<array>
<string>${VENV_PYTHON}</string>
<string>${SCRIPT_DIR}/server.py</string>
PLIST_HEAD
if [ -f "$AFTERWORDS_SERVER_CONFIG" ] && grep -q "^WITH_17B=true" "$AFTERWORDS_SERVER_CONFIG"; then
echo " <string>--with-1.7b</string>"
fi
cat <<PLIST_TAIL
</array>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/>
<key>StandardOutPath</key>
<string>/tmp/claude-tts-server.log</string>
<key>StandardErrorPath</key>
<string>/tmp/claude-tts-server.log</string>
</dict>
</plist>
PLIST_TAIL
} > "$PLIST_PATH"
launchctl unload "$PLIST_PATH" 2>/dev/null || true
launchctl load "$PLIST_PATH"
ok "TTS server will auto-start on login"
# Install CLI to PATH
CLI_SCRIPT="${SCRIPT_DIR}/afterwords.sh"
CLI_LINK="/usr/local/bin/afterwords"
if [ -f "$CLI_SCRIPT" ]; then
if [ -L "$CLI_LINK" ] && [ "$(readlink "$CLI_LINK")" = "$CLI_SCRIPT" ]; then
ok "CLI already on PATH: ${CYAN}afterwords${NC}"
else
info "Adding ${CYAN}afterwords${NC} command to PATH..."
if ln -sf "$CLI_SCRIPT" "$CLI_LINK" 2>/dev/null; then
ok "CLI installed: ${CYAN}afterwords${NC}"
elif sudo ln -sf "$CLI_SCRIPT" "$CLI_LINK" 2>/dev/null; then
ok "CLI installed: ${CYAN}afterwords${NC} (sudo)"
else
warn "Could not symlink to ${CLI_LINK}"
info "Add manually: ${DIM}ln -s ${CLI_SCRIPT} ${CLI_LINK}${NC}"
fi
fi
fi
echo
# ── Verify ────────────────────────────────────────────────────────
printf " ${CYAN}▸${NC} Waiting for server to be ready"
SERVER_OK=false
for i in $(seq 1 60); do
if curl -s --max-time 2 http://127.0.0.1:7860/health | jq -e '.ready == true' &>/dev/null; then
SERVER_OK=true
break
fi
printf "."
sleep 1
done
echo
_ELAPSED=$(( $(date +%s) - _T0 ))
echo
if $SERVER_OK; then
echo -e " ${GREEN}${BOLD}✓ afterwords is running${NC} ${DIM}(setup took ${_ELAPSED}s)${NC}"
else
echo -e " ${YELLOW}${BOLD}⚠ server still starting${NC} ${DIM}(${_ELAPSED}s — model may be downloading)${NC}"
echo
echo -e " ${DIM}Check:${NC} afterwords status"
echo -e " ${DIM}Logs: ${NC} afterwords logs"
fi
echo
rule
echo
echo -e " ${BOLD}Quick reference${NC}"
echo
echo -e " ${CYAN}afterwords status${NC} server state, voices, backends"
echo -e " ${CYAN}afterwords logs${NC} tail server log"
echo -e " ${CYAN}afterwords voices${NC} list cloned voices"
echo -e " ${CYAN}afterwords clone${NC} clone a new voice from YouTube"
echo -e " ${CYAN}afterwords start / stop${NC} start or stop the server"
echo
if $HAS_CLAUDE; then
echo -e " ${BOLD}Claude Code is wired up${NC} — every response will be spoken."
echo -e " Pair with ${CYAN}/voice${NC} (hold Space to dictate) for full voice conversations."
echo
echo -e " ${DIM}per-project voice:${NC} echo \"snape\" > .afterwords"
echo -e " ${DIM}audio archive:${NC} ls ~/.claude/tts-archive/"
else
echo -e " ${BOLD}TTS API is ready${NC} at ${CYAN}http://localhost:7860${NC}"
echo
echo -e " ${DIM}curl \"localhost:7860/synthesize?text=Hello&voice=galadriel\" -o out.wav${NC}"
echo -e " ${DIM}afplay out.wav${NC}"
echo
echo -e " Add any AI agent integration later by re-running ${CYAN}bash setup.sh${NC}"
fi
echo
rule
echo
echo -e " ${BOLD}${DIM}Share this prompt to set up afterwords hands-free:${NC}"
echo
echo -e " ${DIM}┌────────────────────────────────────────────────────────────────────────┐${NC}"
echo -e " ${DIM}│${NC} Clone https://github.com/adrianwedd/afterwords and run bash setup.sh. ${DIM}│${NC}"
echo -e " ${DIM}│${NC} Walk me through each step — ask for a YouTube URL when you need a voice. ${DIM}│${NC}"
echo -e " ${DIM}└────────────────────────────────────────────────────────────────────────┘${NC}"
# ── Codex CLI discovery (optional, per-session) ─────────────────
if command -v codex &>/dev/null; then
echo
rule
echo
echo -e " ${BOLD}Codex CLI detected.${NC}"
echo -e " Afterwords ships a watcher that speaks final Codex responses."
echo -e " ${DIM}Run it from an interactive Codex CLI terminal; hosted/non-interactive sessions may stop background watchers.${NC}"
echo
if [ -n "${CODEX_THREAD_ID:-}" ]; then
echo -e " Inside this Codex session, run:"
echo -e " ${CYAN}afterwords codex-hook start${NC}"
else
echo -e " Inside an interactive Codex session (where ${DIM}\$CODEX_THREAD_ID${NC} is set), run:"
echo -e " ${CYAN}afterwords codex-hook start${NC}"
echo -e " Then ${CYAN}afterwords codex-hook status${NC} to verify, ${CYAN}stop${NC} to quiet."
fi
# Validate Codex-specific dependency: ripgrep
if ! command -v rg &>/dev/null; then
echo
warn "ripgrep (rg) not found — required by the Codex watcher. Install via ${CYAN}brew install ripgrep${NC}."
fi
fi
# ── Gemini CLI discovery (manual config; gemini hooks migrate is buggy) ────
if ! $SERVER_ONLY && command -v gemini &>/dev/null; then
GEMINI_HOOK_DEST="$HOME/.claude/hooks/gemini-tts-hook.sh"
GEMINI_SETTINGS="$HOME/.gemini/settings.json"
echo
rule
echo
echo -e " ${BOLD}Gemini CLI detected.${NC}"
if [ ! -f "$GEMINI_HOOK_DEST" ]; then
cp "$SCRIPT_DIR/.claude/hooks/gemini-tts-hook.sh" "$GEMINI_HOOK_DEST" 2>/dev/null && \
chmod +x "$GEMINI_HOOK_DEST" 2>/dev/null
ok "installed gemini-tts-hook.sh adapter to ~/.claude/hooks/"
fi
echo
echo -e " Gemini's hook payload differs from Claude's, and ${CYAN}gemini hooks migrate${NC} has a"
echo -e " silent-write bug when run from \$HOME. Add this snippet to ${DIM}${GEMINI_SETTINGS}${NC}"
echo -e " manually (merging with any existing keys):"
echo
cat <<'GEMINI_SNIPPET'
{
"hooks": {
"AfterAgent": [
{
"hooks": [
{
"type": "command",
"command": "bash ~/.claude/hooks/gemini-tts-hook.sh",
"timeout": 120000
}
]
}
]
}
}
GEMINI_SNIPPET
echo
echo -e " Test: ${CYAN}gemini -p \"say hi\"${NC} — should speak the response via afterwords."
fi
# ── Antigravity CLI discovery (agy) ──────────────────────────────────────
if ! $SERVER_ONLY && command -v agy &>/dev/null; then
AGY_HOOK_DEST="$HOME/.claude/hooks/agy-tts-hook.sh"
AGY_PYTHON_DEST="$HOME/.claude/hooks/agy-session-hook.py"
AGY_CONFIG_DIR="$HOME/.gemini/config"
AGY_HOOKS_FILE="$AGY_CONFIG_DIR/hooks.json"
echo
rule
echo
echo -e " ${BOLD}Antigravity CLI (agy) detected.${NC}"
if [ ! -f "$AGY_HOOK_DEST" ]; then
cp "$SCRIPT_DIR/.claude/hooks/agy-tts-hook.sh" "$AGY_HOOK_DEST" 2>/dev/null && \
chmod +x "$AGY_HOOK_DEST" 2>/dev/null
ok "installed agy-tts-hook.sh adapter to ~/.claude/hooks/"
fi
if [ ! -f "$AGY_PYTHON_DEST" ]; then
cp "$SCRIPT_DIR/agy_session_hook.py" "$AGY_PYTHON_DEST" 2>/dev/null
ok "installed agy-session-hook.py helper to ~/.claude/hooks/"
fi
# Auto-update ~/.gemini/config/hooks.json
mkdir -p "$AGY_CONFIG_DIR"
if [ -f "$AGY_HOOKS_FILE" ]; then
if jq -e '."afterwords-tts".Stop[]? | select(.command == "bash ~/.claude/hooks/agy-tts-hook.sh")' "$AGY_HOOKS_FILE" &>/dev/null; then
ok "Afterwords hook already registered in ~/.gemini/config/hooks.json"
else
info "Registering/updating Afterwords hook in ~/.gemini/config/hooks.json..."
jq '."afterwords-tts" = {"Stop": [{"type": "command", "command": "bash ~/.claude/hooks/agy-tts-hook.sh", "timeout": 120000}]}' "$AGY_HOOKS_FILE" > "$AGY_HOOKS_FILE.tmp" && \
mv "$AGY_HOOKS_FILE.tmp" "$AGY_HOOKS_FILE"
ok "added/updated Afterwords hook in ~/.gemini/config/hooks.json"
fi
else
info "Creating ~/.gemini/config/hooks.json with Afterwords hook..."
echo '{"afterwords-tts": {"Stop": [{"type": "command", "command": "bash ~/.claude/hooks/agy-tts-hook.sh", "timeout": 120000}]}}' > "$AGY_HOOKS_FILE"
ok "created ~/.gemini/config/hooks.json"
fi
echo
echo -e " Test: ${CYAN}agy --print \"say hi\"${NC} — should speak the response via afterwords."
fi
# ── Cursor IDE discovery ──────────────────────────────────────────────────
if ! $SERVER_ONLY && { [ -d "/Applications/Cursor.app" ] || command -v cursor &>/dev/null || [ -d "$HOME/.cursor" ]; }; then
CURSOR_HOOK_SRC="$SCRIPT_DIR/.claude/hooks/cursor-tts-hook.sh"
CURSOR_HOOK_DEST="$HOME/.claude/hooks/cursor-tts-hook.sh"
CURSOR_HOOKS_FILE="$HOME/.cursor/hooks.json"
echo
rule
echo
echo -e " ${BOLD}Cursor IDE detected.${NC}"
if [ -f "$CURSOR_HOOK_SRC" ]; then
cp "$CURSOR_HOOK_SRC" "$CURSOR_HOOK_DEST" 2>/dev/null && \
chmod +x "$CURSOR_HOOK_DEST" 2>/dev/null
ok "installed cursor-tts-hook.sh to ~/.claude/hooks/"
fi
HOOK_ENTRY='{"command":"bash ~/.claude/hooks/cursor-tts-hook.sh","type":"command","timeout":10,"failClosed":false}'
if [ -f "$CURSOR_HOOKS_FILE" ]; then
if jq -e '.hooks.afterAgentResponse[]? | select(.command == "bash ~/.claude/hooks/cursor-tts-hook.sh")' "$CURSOR_HOOKS_FILE" &>/dev/null; then
ok "Afterwords hook already registered in ~/.cursor/hooks.json"
else
info "Registering Afterwords hook in ~/.cursor/hooks.json..."
jq --argjson entry "$HOOK_ENTRY" \
'.hooks.afterAgentResponse = ((.hooks.afterAgentResponse // []) + [$entry]) | .version = (.version // 1)' \
"$CURSOR_HOOKS_FILE" > "${CURSOR_HOOKS_FILE}.tmp" && \
mv "${CURSOR_HOOKS_FILE}.tmp" "$CURSOR_HOOKS_FILE"
ok "registered Afterwords hook in ~/.cursor/hooks.json"
fi
else
mkdir -p "$(dirname "$CURSOR_HOOKS_FILE")"
printf '{"version":1,"hooks":{"afterAgentResponse":[%s]}}\n' "$HOOK_ENTRY" > "$CURSOR_HOOKS_FILE"
ok "created ~/.cursor/hooks.json with Afterwords hook"
fi
echo
echo -e " Voice per project: add a ${DIM}.afterwords${NC} file at the repo root, e.g.:"
echo -e " ${DIM}cursor: lister${NC}"
echo -e " Then ${CYAN}afterwords reload${NC} after adding new voices."
echo
echo -e " Test: open Cursor agent, ask anything — afterwords should speak the response."
fi
# ── Afterwords menubar app (optional) ────────────────────────────────────
if ! $SERVER_ONLY && [ ! -d "/Applications/Afterwords.app" ]; then
echo
rule
echo
echo -e " ${BOLD}Afterwords menubar app${NC} ${DIM}— optional${NC}"
echo -e " A macOS status-bar app that shows server state, voices, and playback."
echo
AFTERWORDS_APP_REPO="$HOME/repos/afterwords-app"
if [ -d "$AFTERWORDS_APP_REPO" ]; then
ask "Build and install Afterwords.app from ${DIM}${AFTERWORDS_APP_REPO}${NC}? [y/N]:"
read -r BUILD_APP
if [[ "$BUILD_APP" =~ ^[Yy] ]]; then
if command -v xcodegen &>/dev/null; then
info "Building Afterwords.app…"
if (cd "$AFTERWORDS_APP_REPO" && make build 2>&1 | tail -5); then
BUILT_APP="$AFTERWORDS_APP_REPO/build/DerivedData/Build/Products/Debug/Afterwords.app"
[ ! -d "$BUILT_APP" ] && BUILT_APP="$AFTERWORDS_APP_REPO/build/DerivedData/Build/Products/Release/Afterwords.app"
if [ -d "$BUILT_APP" ]; then
cp -r "$BUILT_APP" /Applications/Afterwords.app
ok "Afterwords.app installed to /Applications/"
open /Applications/Afterwords.app
else
warn "Build finished but Afterwords.app not found in expected location."
fi
else
warn "Build failed — check Xcode project setup."
fi
else
warn "xcodegen not found. Install: ${CYAN}brew install xcodegen${NC}, then run ${CYAN}make build${NC} in ${AFTERWORDS_APP_REPO}."
fi
else
info "Skipping app install — get it later: https://github.com/adrianwedd/afterwords-app"
fi
else
echo -e " Get it from: ${CYAN}https://github.com/adrianwedd/afterwords-app${NC}"
echo -e " ${DIM}git clone https://github.com/adrianwedd/afterwords-app.git ~/repos/afterwords-app${NC}"
echo -e " ${DIM}cd ~/repos/afterwords-app && make build${NC}"
fi
fi
echo