-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·3188 lines (2886 loc) · 123 KB
/
Copy pathinstall.sh
File metadata and controls
executable file
·3188 lines (2886 loc) · 123 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# Lowkey Agent — One-Shot Installer
# Usage: curl -sfL https://raw.githubusercontent.com/inceptionstack/loki-agent/main/install.sh -o /tmp/loki-install.sh && bash /tmp/loki-install.sh
# Flags: --non-interactive / -y Accept all defaults, minimal prompts
# --pack <name> Pre-select agent pack (e.g. --pack claude-code, --pack openclaw)
# --method <m> Pre-select deploy method: cfn, terraform (or tf)
# --debug-in-repo Copy local repo to /tmp instead of cloning (for local testing)
# Require bash — printf -v and other bashisms won't work in dash/sh
if [ -z "${BASH_VERSION:-}" ]; then
echo "This script requires bash. Run with: bash $0" >&2; exit 1
fi
set -euo pipefail
# Save original dir before changing (needed for --debug-in-repo)
_ORIG_DIR="$(pwd)"
# Ensure we run from a safe CWD — avoid interference from local .env, direnv, etc.
# (--debug-in-repo will cd back after arg parsing)
cd "$HOME" 2>/dev/null || cd /tmp
export AWS_PAGER=""
export PAGER=""
aws() { command aws --no-cli-pager "$@"; }
# Persistent log file for debugging (survives script exit)
INSTALL_LOG="/tmp/loki-install.log"
: > "$INSTALL_LOG"
show_debug_locations() {
echo -e "\033[1;33m Debug info:\033[0m" >&2
if [[ -s "${INSTALL_LOG:-}" ]]; then
echo -e "\033[1;33m Installer log: ${INSTALL_LOG}\033[0m" >&2
fi
if [[ -s "${_TF_LOG:-}" ]]; then
echo -e "\033[1;33m Terraform log: ${_TF_LOG}\033[0m" >&2
fi
if [[ -n "${CLONE_DIR:-}" && "${CLONE_DIR}" == /tmp/* && -d "$CLONE_DIR" ]]; then
echo -e "\033[1;33m Clone dir: ${CLONE_DIR}\033[0m" >&2
fi
if [[ -n "${TF_WORKDIR:-}" && -d "$TF_WORKDIR" ]]; then
echo -e "\033[1;33m Terraform dir: ${TF_WORKDIR}\033[0m" >&2
fi
}
# Ctrl-C: kill background jobs and exit immediately
cleanup_on_interrupt() {
echo -e "\n\033[0;31m✗ Interrupted\033[0m" >&2
# Kill all child processes (terraform, gum, tee, etc.)
kill -- -$$ 2>/dev/null || kill 0 2>/dev/null
exit 130
}
trap cleanup_on_interrupt INT TERM
# Always show debug info on non-zero exit (EXIT trap is more reliable than ERR)
trap '
exit_code=$?
if [[ $exit_code -ne 0 ]]; then
echo -e "\n\033[0;31m✗ Installer failed (exit code $exit_code)\033[0m" >&2
show_debug_locations
if [[ -z "${_TELEM_FINAL_STATE:-}" ]]; then
# Telemetry: report failure (silently, never blocks >2s)
_telem_install_failed "$exit_code" "${_TELEM_CURRENT_STEP:-unknown}" 2>/dev/null || true
fi
fi
' EXIT
# Track which step we're in (for failure attribution in telemetry)
_TELEM_CURRENT_STEP="init"
REPO_URL="https://github.com/inceptionstack/loki-agent.git"
DOCS_URL="https://github.com/inceptionstack/loki-agent/wiki"
TEMPLATE_RAW_URL="https://raw.githubusercontent.com/inceptionstack/loki-agent/main/deploy/cloudformation/template.yaml"
SSM_DOC_NAME=""
INSTALLER_VERSION="0.5.174"
# ── Telemetry ────────────────────────────────────────────────────────────
# Fire-and-forget telemetry. Opt-out: LOWKEY_TELEMETRY=0 / DO_NOT_TRACK=1
# / ~/.lowkey/telemetry-off. 2s hard timeout, silent on every failure,
# never blocks install. Payloads documented at:
# https://docs.lowkey.run/reference/telemetry-privacy
# https://docs.lowkey.run/reference/telemetry-schema
# Safe no-op fallbacks first — overwritten below. Keeps install hooks
# defined under set -euo pipefail even if something in the block below
# fails to load (e.g. partial download).
_TELEM_LIB_READY=0
_TELEM_FINAL_STATE=""
_telem_install_started() { :; }
_telem_pack_selected() { :; }
_telem_method_selected() { :; }
_telem_deploy_started() { :; }
_telem_deploy_completed() { :; }
_telem_bootstrap_completed(){ :; }
_telem_install_completed() { :; }
_telem_install_failed() { :; }
_telem_event() { :; }
# ── Telemetry implementation ─────────────────────────────────────────
# All functions below are prefixed _telem_ to avoid collisions.
# Fire-and-forget, 2-second timeouts, silent on every failure.
# Opt-out: LOWKEY_TELEMETRY=0 | DO_NOT_TRACK=1 | ~/.lowkey/telemetry-off
# ── Config ──────────────────────────────────────────────────────────────
_TELEM_ENDPOINT="${LOWKEY_TELEMETRY_URL:-https://telemetry.loki.run}"
_TELEM_TIMEOUT=2 # seconds — curl connect + transfer
_TELEM_LOG="${INSTALL_LOG:-/tmp/loki-install.log}"
_TELEM_QUEUE="/tmp/.lowkey-telem-$$" # per-process event queue (NDJSON)
_TELEM_ENABLED=true
_TELEM_INSTALL_ID=""
_TELEM_MACHINE_ID=""
_TELEM_SESSION_ID=""
_TELEM_T0="" # epoch ms when install started
_TELEM_FINAL_STATE="${_TELEM_FINAL_STATE:-}"
_telem_num_or_default() {
local value="${1:-}"
local fallback="${2:-0}"
if [[ "$value" =~ ^[0-9]+$ ]]; then
printf '%s\n' "$value"
else
printf '%s\n' "$fallback"
fi
}
# ── Opt-out check ───────────────────────────────────────────────────────
_telem_init() {
# Respect all three opt-out signals
if [[ "${LOWKEY_TELEMETRY:-}" == "0" ]] \
|| [[ "${DO_NOT_TRACK:-}" == "1" ]] \
|| [[ -n "${HOME:-}" && -f "${HOME}/.lowkey/telemetry-off" ]]; then
_TELEM_ENABLED=false
return 0
fi
# Require curl — if missing, silently disable
if ! command -v curl &>/dev/null; then
_TELEM_ENABLED=false
return 0
fi
# IDs — validate against schema; if we can't produce a conformant machine_id,
# disable telemetry rather than send payloads that will 400.
_TELEM_INSTALL_ID="$(_telem_uuid)"
_TELEM_SESSION_ID="$(_telem_uuid)"
_TELEM_MACHINE_ID="$(_telem_machine_id)"
_TELEM_T0="$(_telem_epoch_ms)"
local os_name arch_name os_ver version os_ver_re
os_name="$(_telem_norm_os)"
arch_name="$(_telem_norm_arch)"
os_ver="$(_telem_norm_os_version)"
version="$(_telem_norm_version)"
os_ver_re='^[-A-Za-z0-9./_+ ]{1,48}$'
if [[ -z "$_TELEM_MACHINE_ID" ]] \
|| [[ -z "$os_name" ]] \
|| [[ -z "$arch_name" ]] \
|| ! [[ "$_TELEM_INSTALL_ID" =~ ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$ ]] \
|| ! [[ "$version" =~ ^[A-Za-z0-9][A-Za-z0-9.+_-]*$ ]] \
|| ! [[ "$os_ver" =~ $os_ver_re ]]; then
_TELEM_ENABLED=false
return 0
fi
# Init the event queue file
: > "$_TELEM_QUEUE" 2>/dev/null || _TELEM_ENABLED=false
}
# ── Identity ────────────────────────────────────────────────────────────
_telem_machine_id() {
# Stable, irreversible machine fingerprint. Never transmitted raw.
local raw=""
if [[ -f /etc/machine-id ]]; then
raw="$(cat /etc/machine-id 2>/dev/null || printf '')"
elif [[ -f /var/lib/dbus/machine-id ]]; then
raw="$(cat /var/lib/dbus/machine-id 2>/dev/null || printf '')"
elif command -v ioreg &>/dev/null; then
raw="$(ioreg -rd1 -c IOPlatformExpertDevice 2>/dev/null | awk -F\" '/IOPlatformUUID/{print $4}' 2>/dev/null || printf '')"
fi
# Mix with hostname for extra uniqueness, hash it
raw="${raw}:$(hostname 2>/dev/null || printf 'unknown')"
# Validate: schema requires sha256:<64-lowercase-hex>. Empty → disable.
local hex=""
if command -v sha256sum &>/dev/null; then
hex="$(printf '%s' "$raw" | sha256sum 2>/dev/null | cut -d' ' -f1 2>/dev/null || printf '')"
elif command -v shasum &>/dev/null; then
hex="$(printf '%s' "$raw" | shasum -a 256 2>/dev/null | cut -d' ' -f1 2>/dev/null || printf '')"
fi
if [[ "$hex" =~ ^[0-9a-f]{64}$ ]]; then
printf 'sha256:%s\n' "$hex"
else
printf ''
fi
}
_telem_uuid() {
# UUIDv4 from /dev/urandom — no external deps
if [[ -r /proc/sys/kernel/random/uuid ]]; then
cat /proc/sys/kernel/random/uuid 2>/dev/null || printf '00000000-0000-4000-8000-000000000000\n'
elif command -v uuidgen &>/dev/null; then
uuidgen 2>/dev/null | tr '[:upper:]' '[:lower:]' 2>/dev/null || printf '00000000-0000-4000-8000-000000000000\n'
else
# Pure bash fallback
local hex
hex="$(od -An -tx1 -N16 /dev/urandom 2>/dev/null | tr -d ' \n' 2>/dev/null || printf '')"
if [[ ${#hex} -ge 32 ]]; then
printf '%s-%s-4%s-%s-%s\n' \
"${hex:0:8}" "${hex:8:4}" "${hex:13:3}" "${hex:16:4}" "${hex:20:12}"
else
printf '00000000-0000-4000-8000-%012d\n' "$$"
fi
fi
}
_telem_epoch_ms() {
# Milliseconds since epoch. Falls back to seconds * 1000.
if date +%s%3N >/dev/null 2>&1; then
local ms
ms="$(_telem_num_or_default "$(date +%s%3N 2>/dev/null || printf '')" '')"
# GNU date returns ms, but macOS date may not support %3N
if [[ ${#ms} -ge 13 ]]; then
printf '%s\n' "$ms"
else
printf '%s000\n' "$(_telem_num_or_default "$(date +%s 2>/dev/null || printf '')" 0)"
fi
else
printf '%s000\n' "$(_telem_num_or_default "$(date +%s 2>/dev/null || printf '')" 0)"
fi
}
_telem_iso() {
# ISO 8601 UTC timestamp
local ts
ts="$(LC_ALL=C date -u +"%Y-%m-%dT%H:%M:%SZ" 2>/dev/null || printf '')"
if [[ "$ts" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$ ]]; then
printf '%s\n' "$ts"
else
printf '1970-01-01T00:00:00Z\n'
fi
}
_telem_duration_ms() {
# Duration since _TELEM_T0 in milliseconds
local now start
now="$(_telem_num_or_default "$(_telem_epoch_ms)" 0)"
start="$(_telem_num_or_default "${_TELEM_T0:-}" 0)"
printf '%s\n' "$(( now - start ))"
}
# ── Normalization helpers ──────────────────────────────────────────────
# Keep outputs strictly within the schema enums.
_telem_norm_os() {
# Map raw uname -s to schema enum: linux | darwin | windows
local s
s="$(uname -s 2>/dev/null | tr '[:upper:]' '[:lower:]' 2>/dev/null || printf 'linux')"
case "$s" in
darwin*) printf 'darwin\n' ;;
linux*) printf 'linux\n' ;;
mingw*|msys*|cygwin*|windows*) printf 'windows\n' ;;
*) printf '' ;;
esac
}
_telem_norm_arch() {
# Map raw uname -m / hw_arch to schema enum: arm64 | x86_64
local a
a="$(hw_arch 2>/dev/null || uname -m 2>/dev/null || printf 'x86_64')"
a="$(printf '%s' "$a" | tr '[:upper:]' '[:lower:]' 2>/dev/null || printf '')"
case "$a" in
arm64|aarch64|armv8*|armv9*) printf 'arm64\n' ;;
x86_64|amd64|x64) printf 'x86_64\n' ;;
*) printf '' ;;
esac
}
_telem_norm_os_version() {
# Schema: alnum + . _ + - space, max 48 chars.
local v
v="$(uname -r 2>/dev/null || printf '0.0')"
# Strip anything not in the allowed set, then cap to 48 chars
v="$(printf '%s' "$v" | tr -cd 'A-Za-z0-9._+\- ' 2>/dev/null || printf '0.0')"
v="${v:0:48}"
[[ -n "$v" ]] || v="0.0"
printf '%s\n' "$v"
}
# Resolve the installer delivery channel for the /v1/install beacon.
# Server enum: brew | curl | dmg | msi | pkg. This describes HOW the
# installer bits got onto the machine, not what cloud deploy method the
# user chose. Default to 'curl' since install.lowkey.run is the canonical
# delivery.
_telem_resolve_install_method() {
# CI runs of install.sh fire real beacons before the TEST_MODE guard
# kicks in. Detecting the GitHub Actions runner environment here lets
# dashboards filter on install_method instead of is_test (which is
# validated but not persisted in the data lake).
if [[ "${GITHUB_ACTIONS:-}" == "true" ]]; then
printf 'github-actions\n'; return 0
fi
# Allow override via env for Homebrew/pkg distribution channels later.
# Server enum: brew | curl | dmg | msi | pkg | github-actions.
local m="${LOWKEY_INSTALL_CHANNEL:-}"
m="$(printf '%s' "$m" | tr '[:upper:]' '[:lower:]' 2>/dev/null || printf '')"
case "$m" in
brew|curl|dmg|msi|pkg|github-actions) printf '%s\n' "$m" ;;
*) printf 'curl\n' ;;
esac
}
# Resolve the deploy method to a catalog-compliant slug for telemetry.
# install.sh stores DEPLOY_METHOD as a numeric code (1=cfn-console, 2=cfn-cli,
# 3=terraform) and PRESELECT_METHOD as the raw user input. Both need
# normalization to the server catalog: cfn | terraform | manual | ec2-direct.
#
# Returns empty string when unresolved so callers can omit the prop
# (server validator drops any value not matching the enum, which pollutes
# dashboards with false "cfn" signals if we default).
_telem_resolve_method() {
local m="${DEPLOY_METHOD:-}"
case "$m" in
1|2) printf 'cfn\n'; return 0 ;;
3) printf 'terraform\n'; return 0 ;;
esac
m="${PRESELECT_METHOD:-}"
m="$(printf '%s' "$m" | tr '[:upper:]' '[:lower:]' 2>/dev/null || printf '')"
case "$m" in
cfn|cloudformation) printf 'cfn\n' ;;
terraform|tf) printf 'terraform\n' ;;
manual) printf 'manual\n' ;;
ec2|ec2-direct) printf 'ec2-direct\n' ;;
*) printf '\n' ;; # unresolved — caller omits key
esac
}
_telem_norm_version() {
# Schema: ^[A-Za-z0-9][A-Za-z0-9.+_-]*$, max 32 chars
local v="${INSTALLER_VERSION:-0.0.0}"
v="$(printf '%s' "$v" | tr -cd 'A-Za-z0-9.+_\-' 2>/dev/null || printf '0.0.0')"
# Ensure first char is alnum
case "${v:0:1}" in
[A-Za-z0-9]) : ;;
*) v="0.0.0" ;;
esac
v="${v:0:32}"
[[ -n "$v" ]] || v="0.0.0"
printf '%s\n' "$v"
}
# ── Event recording (local queue, no network) ──────────────────────────
_telem_event() {
# Usage: _telem_event "event.name" '{"key":"value"}'
#
# Spec note: Event.props is REQUIRED (required: ["t","name","props"] in
# $defs/Event). Per-event `oneOf` branches all permit `{}`; an empty object
# is valid. Always emit `props`, defaulting to {} when no props are given.
[[ "$_TELEM_ENABLED" == "true" ]] || return 0
local name="${1:-unknown}"
local props="${2:-}"
local ts
ts="$(_telem_iso)"
# Event.props is REQUIRED per $defs/Event in telemetry-v1.schema.json
# (required: ["t", "name", "props"]). Always emit it, defaulting to {}
# when the caller passes no props or an empty body. An empty object is
# valid against the Event.props schema (no minProperties constraint).
if [[ -z "$props" || "$props" == "{}" ]]; then
props='{}'
fi
printf '{"t":"%s","name":"%s","props":%s}\n' "$ts" "$name" "$props" \
>> "$_TELEM_QUEUE" 2>/dev/null || true
}
# ── Network: fire-and-forget POST ──────────────────────────────────────
_telem_post() {
# Usage: _telem_post "/v1/install" '{"json":"body"}'
# Runs curl in the background. Never blocks. Never fails visibly.
# Logs HTTP status + ms latency to $_TELEM_LOG so drift can be diagnosed
# locally without breaking user-visible behavior.
local path="${1:-}" body="${2:-}"
[[ "$_TELEM_ENABLED" == "true" ]] || return 0
command -v curl >/dev/null 2>&1 || return 0
(
command curl -sSL -X POST \
"${_TELEM_ENDPOINT}${path}" \
-H "Content-Type: application/json" \
--connect-timeout "$_TELEM_TIMEOUT" \
--max-time "$_TELEM_TIMEOUT" \
-d "$body" \
-o /dev/null \
-w "telemetry ${path} http=%{http_code} time=%{time_total}s\n" \
</dev/null \
2>>"$_TELEM_LOG" \
| tee -a "$_TELEM_LOG" >/dev/null || true
) >/dev/null 2>&1 &
disown 2>/dev/null || true
return 0
}
# Validate a string against the spec's Ident regex.
# Returns the value if it matches, else empty.
_telem_ident() {
local v="${1:-}"
[[ "$v" =~ ^[A-Za-z][A-Za-z0-9_.:-]{0,63}$ ]] && printf '%s' "$v"
}
# ── High-level: install beacon (/v1/install) ────────────────────────────
_telem_send_install_beacon() {
# Usage: _telem_send_install_beacon "completed" [duration_ms] [failure_step] [failure_class]
#
# Spec note (openapi-spec.json InstallEnvelope):
# failure_step and failure_class are NOT nullable — they must be OMITTED
# entirely unless outcome=failed AND the value passes the Ident regex.
# Previous code emitted "null" which a strict OpenAPI 3.1 validator rejects.
[[ "$_TELEM_ENABLED" == "true" ]] || return 0
local outcome="${1:-started}"
local duration_ms
local failure_step=""
local failure_class=""
duration_ms="$(_telem_num_or_default "${2:-0}" 0)"
# Only include failure fields when outcome=failed AND they pass Ident regex.
if [[ "$outcome" == "failed" ]]; then
failure_step="$(_telem_ident "${3:-}")"
failure_class="$(_telem_ident "${4:-}")"
fi
local os_name arch_name os_ver install_method
os_name="$(_telem_norm_os)"
arch_name="$(_telem_norm_arch)"
os_ver="$(_telem_norm_os_version)"
install_method="$(_telem_resolve_install_method)"
# Build JSON with failure_step / failure_class OMITTED when empty.
local fs_json="" fc_json=""
[[ -n "$failure_step" ]] && fs_json=",\"failure_step\":\"${failure_step}\""
[[ -n "$failure_class" ]] && fc_json=",\"failure_class\":\"${failure_class}\""
# account_prefix: first 5 digits of AWS account ID (omitted if unavailable)
local ap_json=""
local ap="$(_telem_account_prefix "${ACCOUNT_ID:-}")"
[[ -n "$ap" ]] && ap_json=",\"account_prefix\":\"${ap}\""
local body
body=$(cat <<EOF
{"schema":"lowkey.install.v1","sent_at":"$(_telem_iso)","install_id":"${_TELEM_INSTALL_ID}","machine_id":"${_TELEM_MACHINE_ID}","agent":{"version":"$(_telem_norm_version)","channel":"stable","os":"${os_name}","arch":"${arch_name}","os_version":"${os_ver}"},"install_method":"${install_method}","outcome":"${outcome}","duration_ms":${duration_ms},"is_test":${TEST_MODE:-false},"account_rename_enabled":${AUTO_RENAME_ACCOUNT:-false}${ap_json}${fs_json}${fc_json}}
EOF
)
_telem_post "/v1/install" "$body"
}
# ── High-level: flush queued events (/v1/ingest) ───────────────────────
_telem_flush() {
# Backend catalog was expanded 2026-04-27 to accept install.* names.
# Flush all queued events as one batch. Called at install end.
[[ "$_TELEM_ENABLED" == "true" ]] || return 0
[[ -s "$_TELEM_QUEUE" ]] || return 0 # nothing to send
local os_name arch_name os_ver events
local queue_copy
queue_copy="$(cat "$_TELEM_QUEUE" 2>/dev/null || printf '')"
rm -f "$_TELEM_QUEUE" 2>/dev/null || true
[[ -n "$queue_copy" ]] || return 0
os_name="$(_telem_norm_os)"
arch_name="$(_telem_norm_arch)"
os_ver="$(_telem_norm_os_version)"
# Build the events array from NDJSON lines
events="["
local first=true line
while IFS= read -r line; do
[[ -z "$line" ]] && continue
if [[ "$first" == "true" ]]; then first=false; else events+=","; fi
events+="$line"
done <<< "$queue_copy"
events+="]"
local body
body=$(cat <<EOF
{
"schema": "lowkey.telemetry.v1",
"sent_at": "$(_telem_iso)",
"agent": {
"version": "$(_telem_norm_version)",
"channel": "stable",
"os": "${os_name}",
"arch": "${arch_name}",
"os_version": "${os_ver}"
},
"machine_id": "${_TELEM_MACHINE_ID}",
"install_id": "${_TELEM_INSTALL_ID}",
"session_id": "${_TELEM_SESSION_ID}",
"is_test": ${TEST_MODE:-false},
"events": ${events}
}
EOF
)
_telem_post "/v1/ingest" "$body"
return 0
}
# ── Convenience: record common installer events ────────────────────────
#
# ⚠ IMPORTANT — only these 21 event names are in the server catalog
# (see https://docs.lowkey.run/reference/telemetry-schema and the OpenAPI at
# https://lowkey.run/api/telemetry-v1.openapi.yaml). Unknown event names and
# unwhitelisted props are silently dropped server-side. We do NOT emit
# install.started / install.completed / install.failed as catalog events —
# those are captured by the /v1/install beacon outcome= field instead.
#
# Props are built via _telem_kv so keys with empty or invalid values are
# omitted, rather than sending "unknown" strings that the server drops.
# Build a single "k":"v" pair if value is non-empty; otherwise print nothing.
# Quotes and special JSON chars are NOT escaped because installer values are
# bounded (enums, regex-validated). Use only for controlled inputs.
_telem_kv() {
local k="$1" v="$2"
[[ -n "$v" ]] || return 0
printf '"%s":"%s"' "$k" "$v"
}
_telem_kv_num() {
local k="$1" v="$2"
[[ -n "$v" ]] || return 0
# only emit if purely numeric
[[ "$v" =~ ^[0-9]+$ ]] || return 0
printf '"%s":%s' "$k" "$v"
}
# Join non-empty pairs with commas into a JSON object body.
_telem_props() {
local body="" pair
for pair in "$@"; do
[[ -z "$pair" ]] && continue
[[ -z "$body" ]] && body="$pair" || body="$body,$pair"
done
printf '{%s}' "$body"
}
# Return $1 only if it matches AWS region pattern, else empty.
_telem_aws_region() {
local v="${1:-}"
[[ "$v" =~ ^[a-z]{2}(-[a-z]+)+-[0-9]{1,2}[a-z]?$ ]] && printf '%s' "$v"
}
# Return $1 only if it matches AWS 12-digit account ID pattern, else empty.
_telem_account_prefix() {
local v="${1:-}"
[[ "$v" =~ ^[0-9]{12}$ ]] && printf '%s' "${v:0:5}"
}
# Return $1 only if it's a valid InstallPack enum value, else empty.
_telem_pack() {
local v="${1:-}"
case "$v" in
builder|personal-assistant|account-assistant|essential|optional\
|personal_assistant|account_assistant|openclaw|claude-code|codex-cli\
|kiro-cli|nemoclaw|hermes|pi|ironclaw|roundhouse)
printf '%s' "$v" ;;
esac
}
_telem_profile() {
local v="${1:-}"
case "$v" in
builder|personal_assistant|account_assistant|personal-assistant|account-assistant)
printf '%s' "$v" ;;
esac
}
# Clamp to [0,3600000] (spec max for install.deploy_completed.duration_ms).
_telem_clamp_duration_ms() {
local v="${1:-0}"
[[ "$v" =~ ^[0-9]+$ ]] || { printf '0'; return 0; }
(( v > 3600000 )) && v=3600000
printf '%s' "$v"
}
# Install started: beacon only, no catalog event (install.started is NOT in
# the server catalog and would be silently dropped from /v1/ingest).
_telem_install_started() {
_telem_send_install_beacon "started"
}
_telem_pack_selected() {
local props
props="$(_telem_props \
"$(_telem_kv pack "$(_telem_pack "${PACK_NAME:-}")")" \
"$(_telem_kv profile "$(_telem_profile "${PROFILE_NAME:-}")")")"
_telem_event "install.pack_selected" "$props"
}
_telem_method_selected() {
local props
props="$(_telem_props \
"$(_telem_kv method "$(_telem_resolve_method)")" \
"$(_telem_kv region "$(_telem_aws_region "${DEPLOY_REGION:-}")")")"
_telem_event "install.method_selected" "$props"
}
_telem_deploy_started() {
local props
props="$(_telem_props \
"$(_telem_kv method "$(_telem_resolve_method)")" \
"$(_telem_kv region "$(_telem_aws_region "${DEPLOY_REGION:-}")")" \
"$(_telem_kv pack "$(_telem_pack "${PACK_NAME:-}")")")"
_telem_event "install.deploy_started" "$props"
}
_telem_deploy_completed() {
local dur
dur="$(_telem_clamp_duration_ms "$(_telem_duration_ms)")"
local props
props="$(_telem_props \
"$(_telem_kv method "$(_telem_resolve_method)")" \
"$(_telem_kv_num duration_ms "$dur")")"
_telem_event "install.deploy_completed" "$props"
}
_telem_bootstrap_completed() {
local props
props="$(_telem_props \
"$(_telem_kv account_prefix "$(_telem_account_prefix "${ACCOUNT_ID:-}")")")"
_telem_event "install.bootstrap_completed" "$props"
}
# Install completed: beacon only (install.completed NOT in catalog — would be dropped).
_telem_install_completed() {
[[ -z "${_TELEM_FINAL_STATE:-}" ]] || return 0
_TELEM_FINAL_STATE="completed"
local dur
dur="$(_telem_duration_ms)"
_telem_send_install_beacon "completed" "$dur"
_telem_flush
}
# Install failed: beacon only. failure_step is normalized to the spec's Ident
# regex (^[A-Za-z][A-Za-z0-9_.:-]{0,63}$); anything that doesn't conform is
# sanitized to "unknown_step".
_telem_install_failed() {
[[ -z "${_TELEM_FINAL_STATE:-}" ]] || return 0
_TELEM_FINAL_STATE="failed"
local exit_code="${1:-1}"
local failure_step="${2:-unknown_step}"
[[ "$failure_step" =~ ^[A-Za-z][A-Za-z0-9_.:-]{0,63}$ ]] || failure_step="unknown_step"
local dur
dur="$(_telem_duration_ms)"
_telem_send_install_beacon "failed" "$dur" "$failure_step" "exit_${exit_code}"
_telem_flush
}
# ── Auto-init on source ────────────────────────────────────────────────
_telem_init
_TELEM_LIB_READY=1
# --non-interactive / --yes / -y: accept all defaults, minimal prompts
# --pack <name>: pre-select agent pack
# --method <m>: pre-select deploy method (cfn, terraform/tf)
# --profile <p>: pre-select permission profile (builder, account_assistant, personal_assistant)
# --simple / --advanced: pre-select install mode
# --test: mark this invocation as a test (no AWS deploy, telemetry tagged is_test)
AUTO_YES=false
PRESELECT_PACK=""
PRESELECT_METHOD=""
PRESELECT_PROFILE=""
INSTALL_MODE="" # "simple" or "advanced", empty = ask
DEBUG_IN_REPO=false
TEST_MODE=false
AUTO_RENAME_ACCOUNT=false
DISABLE_ACCOUNT_RENAME=false
while [[ $# -gt 0 ]]; do
case "$1" in
--non-interactive|--yes|-y) AUTO_YES=true; shift ;;
--simple) INSTALL_MODE="simple"; shift ;;
--advanced) INSTALL_MODE="advanced"; shift ;;
--pack)
if [[ $# -lt 2 || "$2" == --* ]]; then
echo -e "\033[0;31m✗\033[0m --pack requires a pack name (e.g. --pack openclaw, --pack claude-code)" >&2
exit 1
fi
PRESELECT_PACK="$2"; shift 2 ;;
--method)
if [[ $# -lt 2 || "$2" == --* ]]; then
echo -e "\033[0;31m✗\033[0m --method requires a value (cfn, terraform, tf)" >&2
exit 1
fi
PRESELECT_METHOD="$2"; shift 2 ;;
--profile)
if [[ $# -lt 2 || "$2" == --* ]]; then
echo -e "\033[0;31m✗\033[0m --profile requires a value (builder, account_assistant, personal_assistant)" >&2
exit 1
fi
PRESELECT_PROFILE="$2"; shift 2 ;;
--kiro-from-secret)
# Secrets Manager id/arn whose SecretString is the Kiro API key.
# Only the secret *reference* passes through CFN/TF state; the raw key
# is resolved on the instance at install time via its IAM role.
if [[ $# -lt 2 || "$2" == --* ]]; then
echo -e "\033[0;31m✗\033[0m --kiro-from-secret requires a Secrets Manager id or arn" >&2
exit 1
fi
KIRO_FROM_SECRET="$2"; shift 2 ;;
--telegram-bot-token)
if [[ $# -lt 2 || "$2" == --* ]]; then
echo -e "\033[0;31m✗\033[0m --telegram-bot-token requires a token value" >&2
exit 1
fi
TELEGRAM_BOT_TOKEN_RAW="$2"; shift 2 ;;
--telegram-bot-token-secret)
if [[ $# -lt 2 || "$2" == --* ]]; then
echo -e "\033[0;31m✗\033[0m --telegram-bot-token-secret requires a Secrets Manager id or arn" >&2
exit 1
fi
TELEGRAM_BOT_TOKEN_SECRET="$2"; shift 2 ;;
--telegram-user)
if [[ $# -lt 2 || "$2" == --* ]]; then
echo -e "\033[0;31m✗\033[0m --telegram-user requires a Telegram username" >&2
exit 1
fi
TELEGRAM_USER="$2"; shift 2 ;;
--debug-in-repo) DEBUG_IN_REPO=true; shift ;;
--test|--dry-run) TEST_MODE=true; shift ;;
--auto-rename-account-enabled) AUTO_RENAME_ACCOUNT=true; shift ;;
--disable-account-rename) DISABLE_ACCOUNT_RENAME=true; shift ;;
--help|-h)
cat <<'USAGE'
Usage: install.sh [OPTIONS]
Deploy a self-hosted AI coding agent to your AWS account.
Options:
-y, --non-interactive, --yes Accept defaults; skip prompts
--simple Force simple install mode
--advanced Force advanced install mode
--pack <name> Agent pack (openclaw, claude-code, codex-cli,
kiro-cli, nemoclaw, hermes, pi, ironclaw,
roundhouse)
--profile <name> Permission profile (builder,
account_assistant, personal_assistant)
--method <cfn|terraform|tf> Deploy method (default: cfn)
--kiro-from-secret <id|arn> Secrets Manager id/arn for Kiro API key
(kiro-cli headless mode)
--telegram-bot-token <token> Telegram bot token (roundhouse pack;
saved to Secrets Manager automatically)
--telegram-bot-token-secret <id|arn>
Secrets Manager id/arn for Telegram bot token
(roundhouse pack, advanced/pre-created)
--telegram-user <username> Telegram username for bot pairing
(roundhouse pack, without @)
--debug-in-repo Dev-only: run installer from cwd
--test, --dry-run Run installer end-to-end without
provisioning AWS resources. Telemetry
hits from this invocation are tagged
is_test and excluded from dashboard stats.
--auto-rename-account-enabled Enable auto-rename of AWS account to
Loki-<name> in headless (-y) mode
--disable-account-rename Skip account rename entirely
-h, --help Show this help and exit
Examples:
curl -sfL install.lowkey.run | bash
curl -sfL install.lowkey.run | bash -s -- -y --pack openclaw --profile builder
curl -sfL install.lowkey.run | bash -s -- -y --pack kiro-cli --profile builder \
--kiro-from-secret /lowkey/kiro-api-key
# Test install (no AWS resources created, not counted in install stats):
curl -sfL "install.lowkey.run?test" | bash -s -- --test
Docs: https://github.com/inceptionstack/lowkey/tree/main/docs
USAGE
exit 0 ;;
*) shift ;;
esac
done
# If --debug-in-repo, go back to the original directory (before cd $HOME)
if [[ "$DEBUG_IN_REPO" == "true" ]]; then
cd "$_ORIG_DIR"
fi
SCRIPT_DIR="$_ORIG_DIR"
# Debug logging — writes to install log only, never to terminal
dbg() {
[[ "$DEBUG_IN_REPO" == "true" ]] && echo "[DBG] $*" >> "$INSTALL_LOG"
return 0
}
# Deploy method constants
DEPLOY_CFN_CONSOLE=1
DEPLOY_CFN_CLI=2
DEPLOY_TERRAFORM=3
# Stamped at release; fall back to git info at runtime
INSTALLER_COMMIT="${INSTALLER_COMMIT:-$(git -C "$SCRIPT_DIR" rev-parse --short HEAD 2>/dev/null || echo dev)}"
INSTALLER_DATE="${INSTALLER_DATE:-$(d=$(git -C "$SCRIPT_DIR" log -1 --format='%ci' 2>/dev/null | cut -d' ' -f1,2); echo "${d:-unknown}")}"
# Only detect branch from git if we're inside the actual lowkey repo (not a random parent repo)
if [[ -z "${REPO_BRANCH:-}" ]]; then
if [[ -f "$SCRIPT_DIR/packs/registry.yaml" ]]; then
REPO_BRANCH="$(git -C "$SCRIPT_DIR" rev-parse --abbrev-ref HEAD 2>/dev/null || echo main)"
else
REPO_BRANCH="main"
fi
fi
[[ "$REPO_BRANCH" == "HEAD" ]] && REPO_BRANCH="main"
# Detect AWS CloudShell (limited ~1GB home dir, use /tmp for large files)
IS_CLOUDSHELL=false
if [[ -n "${AWS_EXECUTION_ENV:-}" && "${AWS_EXECUTION_ENV}" == *"CloudShell"* ]] || [[ -d /home/cloudshell-user && "$(whoami)" == "cloudshell-user" ]]; then
IS_CLOUDSHELL=true
fi
# ============================================================================
# gum — UI toolkit (installed to /tmp, no root required)
# ============================================================================
GUM="" # set by install_gum — required, script fails without it
GUM_VERSION="0.14.5" # fallback version
# ── Shared platform detection ────────────────────────────────────────────────
# Sets DETECTED_OS and DETECTED_ARCH. Accepts optional arch style:
# "go" → amd64/arm64 (Terraform, Go binaries)
# default → x86_64/arm64 (gum, generic)
DETECTED_OS=""
DETECTED_ARCH=""
# Get real hardware arch (uname -m and sysctl hw.machine lie under Rosetta)
hw_arch() {
if [[ "$(sysctl -n hw.optional.arm64 2>/dev/null)" == "1" ]]; then
echo "arm64"
else
uname -m
fi
}
detect_platform() {
local arch_style="${1:-default}"
case "$(uname -s)" in
Darwin) DETECTED_OS="Darwin" ;;
Linux) DETECTED_OS="Linux" ;;
*) DETECTED_OS=""; return 1 ;;
esac
case "$(hw_arch)" in
x86_64|amd64)
if [[ "$arch_style" == "go" ]]; then DETECTED_ARCH="amd64"; else DETECTED_ARCH="x86_64"; fi ;;
aarch64|arm64) DETECTED_ARCH="arm64" ;;
*) DETECTED_ARCH=""; return 1 ;;
esac
}
install_gum() {
# Already installed?
if command -v gum &>/dev/null; then
GUM="gum"; return 0
fi
local gum_bin="/tmp/gum-bin/gum"
if [[ -x "$gum_bin" ]]; then
GUM="$gum_bin"; return 0
fi
detect_platform || fail "Unsupported OS/architecture for gum: $(uname -s)/$(uname -m)"
local os="$DETECTED_OS" arch="$DETECTED_ARCH"
# Try to get latest version from GitHub API, fall back to known good
local version
version=$(curl -sf https://api.github.com/repos/charmbracelet/gum/releases/latest 2>/dev/null \
| grep '"tag_name"' | head -1 | sed 's/.*"v\([^"]*\)".*/\1/' || echo "")
[[ -z "$version" ]] && version="$GUM_VERSION"
local url="https://github.com/charmbracelet/gum/releases/download/v${version}/gum_${version}_${os}_${arch}.tar.gz"
mkdir -p /tmp/gum-bin
if curl -sfL "$url" | tar xz --strip-components=1 -C /tmp/gum-bin 2>/dev/null; then
chmod +x "$gum_bin"
GUM="$gum_bin"
else
fail "Could not install gum. Check network connectivity and try again."
fi
}
# ============================================================================
# UI helpers
# ============================================================================
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; BLUE='\033[0;34m'; CYAN='\033[0;36m'; BOLD='\033[1m'; DIM='\033[2m'; NC='\033[0m'
MAGENTA='\033[0;35m'; WHITE='\033[1;37m'
info() { echo -e " ${BLUE}▸${NC} $1"; }
ok() { echo -e " ${GREEN}✓${NC} $1"; }
warn() { echo -e " ${YELLOW}⚠${NC} $1"; }
fail() { echo -e " ${RED}✗${NC} $1"; show_debug_locations; exit 1; }
# ── Elapsed time formatting ──────────────────────────────────────────────────
elapsed_fmt() {
local secs=$1
if [[ $secs -lt 60 ]]; then
printf '%ds' "$secs"
else
printf '%dm %ds' "$((secs / 60))" "$((secs % 60))"
fi
}
# ── Step progress tracker ────────────────────────────────────────────────────
STEP_NUM=0
TOTAL_STEPS=7
STEP_NAMES=()
step() {
STEP_NUM=$((STEP_NUM + 1))
STEP_NAMES+=("$1")
echo ""
$GUM style --foreground 117 --bold --border double --border-foreground 240 \
--padding "0 2" --margin "0 2" "[${STEP_NUM}/${TOTAL_STEPS}] $1"
echo ""
}
prompt() {
local text="$1" var="$2" default="${3:-}"
if [[ "$AUTO_YES" == true && -n "$default" ]]; then
printf -v "$var" '%s' "$default"
return
fi
local value
_gum_or_die value $GUM input --header "$text" --value "$default" --placeholder "$text" || value="$default"
printf -v "$var" '%s' "${value:-$default}"
}
prompt_secret() {
local text="$1" var="$2" default="${3:-}"
if [[ "$AUTO_YES" == true && -n "$default" ]]; then
printf -v "$var" '%s' "$default"
return
fi
local value
_gum_or_die value $GUM input --password --header "$text" --placeholder "$text" || value="$default"
printf -v "$var" '%s' "${value:-$default}"
}
confirm() {
local text="$1" default="${2:-default_no}"
if [[ "$AUTO_YES" == true ]]; then return 0; fi
local rc=0
if [[ "$default" == "default_yes" ]]; then
$GUM confirm --default=yes "$text" < /dev/tty || rc=$?
else
$GUM confirm "$text" < /dev/tty || rc=$?
fi
[[ $rc -eq 130 ]] && { echo ""; cleanup_on_interrupt; }
return $rc
}
toggle() {
local text="$1" var="$2" default="${3:-true}"
if [[ "$AUTO_YES" == true ]]; then
printf -v "$var" '%s' "$default"
return
fi
local rc=0
if [[ "$default" == "true" ]]; then
$GUM confirm --default=yes " $text" < /dev/tty || rc=$?
else
$GUM confirm " $text" < /dev/tty || rc=$?
fi
[[ $rc -eq 0 ]] && printf -v "$var" '%s' "true" || printf -v "$var" '%s' "false"
}
require_cmd() { command -v "$1" &>/dev/null || fail "$2"; }
# Run a gum command; if it exits with 130 (SIGINT/Ctrl-C), abort the installer.
# Usage: _gum_or_die result_var gum_command [args...]
# On success: sets result_var to gum's stdout, returns 0
# On Ctrl-C (exit 130): exits the installer immediately
# On other failure (Escape, etc): returns 1 (caller handles fallback)
_gum_or_die() {
local __var="$1"; shift
local __out __rc=0
__out=$("$@" < /dev/tty) || __rc=$?
if [[ $__rc -eq 130 ]]; then
echo ""
cleanup_on_interrupt
fi
printf -v "$__var" '%s' "$__out"
return $__rc
}
# Confirm or exit cleanly
confirm_or_abort() { confirm "$@" || { echo "Aborted."; exit 0; }; }
# Extract a key from JSON on stdin
json_field() { jq -r ".$1" 2>/dev/null; }
# URL-encode a string
url_encode() { jq -rn --arg s "$1" '$s | @uri'; }
# ── Reusable helpers (DRY) ──────────────────────────────────────────────────
# Animate a gum spinner with label for N seconds.
# Usage: animate_spinner <seconds> <label>
animate_spinner() {
local total_secs="$1" label="$2"
$GUM spin --spinner dot --title " $label" -- sleep "$total_secs" || true