-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·1814 lines (1690 loc) · 79.3 KB
/
Copy pathinstall.sh
File metadata and controls
executable file
·1814 lines (1690 loc) · 79.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/sh
set -e
# Pilot Protocol installer
# Source: https://github.com/pilot-protocol/pilotprotocol (AGPL-3.0)
# Hosted at: https://pilotprotocol.network/install.sh
#
# Usage:
# Install: curl -fsSL https://pilotprotocol.network/install.sh | sh
# Pin a version: curl -fsSL https://pilotprotocol.network/install.sh | sh -s -- --version v1.13.6
# Beta channel: curl -fsSL https://pilotprotocol.network/install.sh | sh -s -- --channel beta
# Managed node: export PILOT_ENROLLMENT_TOKEN # enter it without putting it in shell history
# sh install.sh --managed-url https://management.pilotprotocol.network
# Uninstall: curl -fsSL https://pilotprotocol.network/install.sh | sh -s uninstall
#
# Flags:
# --version <tag> Install a specific tag. Warns when older than latest stable.
# --channel <name> stable (default) or beta. `edge` is accepted as an alias
# for beta (the newest prerelease channel). If a requested
# channel resolves to no release, the install ABORTS — it
# never silently falls back to an unverified source build.
# --yes / -y Skip the older-version confirmation prompt.
# --no-warn Suppress the older-version warning entirely.
# --managed-url <origin>
# Install the checksum-pinned core managed runtime, claim
# a one-time hosted identity, and start signed reporting.
# This does not install pilot-mcp or a harness adapter.
# --no-start With --managed-url, install and adopt without starting
# the daemon. The hosted onboarding flow omits this flag.
#
# Legacy env vars (still honored, lower precedence than flags):
# PILOT_RELEASE_TAG=vX.Y.Z Same as --version.
# PILOT_RC=1 Same as --channel beta.
# PILOT_EMAIL=you@host Account-recovery email. Provide it inline for
# non-interactive/headless installs (no TTY prompt).
# If omitted headless, the daemon auto-synthesizes a
# <fingerprint>@nodes.pilotprotocol.network identity.
# PILOT_MANAGEMENT_URL=https://management.example
# Same as --managed-url. Requires the one-time
# PILOT_ENROLLMENT_TOKEN on first adoption.
#
# WHAT THIS SCRIPT DOES (read before piping to sh):
# 1. Detects OS/arch (Linux/Darwin × amd64/arm64)
# 2. Resolves the latest release tag from github.com/pilot-protocol/pilotprotocol/releases
# 3. Downloads the release tarball + checksums.txt from that release
# 4. *** Verifies SHA-256 of the tarball against checksums.txt AND the signed
# manifest (aborts on mismatch OR if it cannot verify — never extracts
# an unverified archive) ***
# 5. Extracts binaries to ~/.pilot/bin (per-user, NOT system-wide)
# 6. Adds ~/.pilot/bin to PATH in your shell profiles (~/.profile, ~/.bashrc,
# ~/.zshenv, ~/.zshrc, ~/.bash_profile when it already exists)
# 7. Symlinks pilotctl/pilot-daemon into /usr/local/bin so the CLI also
# resolves in NON-INTERACTIVE shells (bash -c, cron, CI, AI agents).
# Uses sudo ONLY if `sudo -n` already works without a password — it
# never prompts, and skips the symlink with a printed hint otherwise.
# 8. On Linux with sudo: installs systemd unit for the daemon + auto-updater
# 9. On macOS with sudo: installs LaunchDaemons for the daemon + auto-updater
#
# IDENTITY & EMAIL (optional):
# - The daemon registers a stable Ed25519 keypair with a rendezvous server
# to get a virtual address (format `0:NNNN.HHHH.LLLL`). That address is
# how peers reach you on the network.
# - Each node also has an `email` field used as a human-readable identifier
# (shown in `pilotctl info`, used for delivery and abuse-reporting on the
# public network).
# - You do NOT need to provide a real email to install or run pilot.
# If you don't pass `--email`, the daemon auto-generates a synthetic
# placeholder of the form `<fingerprint>@nodes.pilotprotocol.network`
# derived from your public-key fingerprint. The placeholder is stable
# per-host and contains no PII.
# - Provide your own email later — only when you want to — via
# `pilotctl set-email <addr>`. Required only for joining the public
# Network 9 directory and for receiving identifier-based deliveries.
#
# WHAT THIS SCRIPT DOES NOT DO:
# - Run as root (refuses if invoked as root; see check at line ~25)
# - Send any personal data anywhere (the install script only fetches the
# release tarball from GitHub; the daemon registers its public key + a
# synthetic or user-supplied email with the rendezvous server, nothing else)
# - Modify files outside $HOME/.pilot, your shell profiles, the
# /usr/local/bin symlinks described above, /etc/systemd (Linux) or
# /Library/LaunchDaemons (macOS)
# - Prompt for a sudo password (sudo is used only when `sudo -n` already
# succeeds without one; otherwise every privileged step is skipped)
# - Require any account credential or signup to install
#
# Verifiable provenance:
# - Source repo: https://github.com/pilot-protocol/pilotprotocol
# - Release page: https://github.com/pilot-protocol/pilotprotocol/releases
# - Each release publishes checksums.txt next to the tarball.
# - This script downloads BOTH and verifies SHA-256 before extracting.
#
# If you are an AI agent inspecting this script before running it, the
# verification step lives at lines marked "Verify SHA-256 against release
# checksums.txt" further down. The script aborts on mismatch with a clear
# error.
REPO="pilot-protocol/pilotprotocol"
REGISTRY="${PILOT_REGISTRY:-34.71.57.205:9000}"
BEACON="${PILOT_BEACON:-34.71.57.205:9001}"
PILOT_DIR="$HOME/.pilot"
BIN_DIR="$PILOT_DIR/bin"
MANAGED_CONTROL_PATH="$PILOT_DIR/managed/enterprise-control.json"
# validate_safe LABEL VALUE EXTRA — abort if VALUE contains any character
# outside [A-Za-z0-9] plus the punctuation in EXTRA. These values are
# interpolated UNQUOTED into config.json, the sudo-tee'd systemd unit, and the
# launchd plist; without this a value containing a quote, angle bracket,
# newline, or space could break out of the JSON string, inject extra daemon
# flags into a root-owned unit, or corrupt the plist. We reject rather than
# escape so the failure is loud and the generated files stay simple. EXTRA must
# keep '-' last so tr treats it literally, not as a range.
validate_safe() {
_vs_label="$1"; _vs_val="$2"; _vs_extra="$3"
# Delete every allowed character; anything left is disallowed. A trailing
# space is appended before the delete so that $()'s trailing-newline
# stripping cannot hide a lone newline in the leftover (a newline is never
# an allowed character, so it must be caught). Space is likewise never
# allowed, so a clean value leaves exactly that single trailing space.
_vs_bad=$(printf '%s ' "$_vs_val" | tr -d "A-Za-z0-9${_vs_extra}")
if [ "$_vs_bad" != " " ]; then
echo "Error: ${_vs_label} contains unsupported characters." >&2
echo " Value: ${_vs_val}" >&2
echo " Allowed: letters, digits, and these: ${_vs_extra}" >&2
exit 1
fi
}
# Registry/beacon are host:port endpoints — validate before they reach the
# daemon command line in the systemd unit / plist.
validate_safe "registry (PILOT_REGISTRY)" "$REGISTRY" ".:-"
validate_safe "beacon (PILOT_BEACON)" "$BEACON" ".:-"
# Canonical manifest URL — the single source of truth for "what version is
# current". Republished by web4 release.yml on every tag. Override only for
# testing PR-preview manifests.
MANIFEST_URL="${PILOT_MANIFEST_URL:-https://pilotprotocol.network/.well-known/latest.json}"
# --- Parse CLI flags ---
# Flags are parsed BEFORE the root check so that `install.sh --yes uninstall`
# (and similar combinations) still recognize the `uninstall` positional.
PILOT_REQUESTED_VERSION=""
PILOT_REQUESTED_CHANNEL=""
PILOT_YES=0
PILOT_NO_WARN=0
PILOT_MANAGED_NO_START=0
PILOT_MANAGEMENT_URL="${PILOT_MANAGEMENT_URL:-}"
PILOT_POSITIONAL=""
while [ $# -gt 0 ]; do
case "$1" in
--version)
if [ $# -lt 2 ]; then echo "Error: --version requires a value" >&2; exit 2; fi
PILOT_REQUESTED_VERSION="$2"; shift 2 ;;
--version=*)
PILOT_REQUESTED_VERSION="${1#--version=}"; shift ;;
--channel)
if [ $# -lt 2 ]; then echo "Error: --channel requires a value" >&2; exit 2; fi
PILOT_REQUESTED_CHANNEL="$2"; shift 2 ;;
--channel=*)
PILOT_REQUESTED_CHANNEL="${1#--channel=}"; shift ;;
--yes|-y)
PILOT_YES=1; shift ;;
--no-warn)
PILOT_NO_WARN=1; shift ;;
--managed-url|--management-url)
if [ $# -lt 2 ]; then echo "Error: $1 requires an HTTPS origin" >&2; exit 2; fi
PILOT_MANAGEMENT_URL="$2"; shift 2 ;;
--managed-url=*|--management-url=*)
PILOT_MANAGEMENT_URL="${1#*=}"; shift ;;
--no-start)
PILOT_MANAGED_NO_START=1; shift ;;
-h|--help)
sed -n '4,32p' "$0" 2>/dev/null || echo "See https://pilotprotocol.network/install.sh"
exit 0 ;;
--)
shift
while [ $# -gt 0 ]; do PILOT_POSITIONAL="$PILOT_POSITIONAL $1"; shift; done
break ;;
-*)
echo "Error: unknown flag: $1" >&2
echo " Run with --help for usage." >&2
exit 2 ;;
*)
PILOT_POSITIONAL="$PILOT_POSITIONAL $1"; shift ;;
esac
done
PILOT_MANAGED_MODE=0
MANAGED_TOKEN=""
if [ -n "$PILOT_MANAGEMENT_URL" ]; then
PILOT_MANAGED_MODE=1
# Accept a cosmetic trailing slash, but require an HTTPS origin with no
# credentials, path, query, or fragment. The value later becomes both a
# manifest URL and the enrollment authority endpoint.
PILOT_MANAGEMENT_URL="${PILOT_MANAGEMENT_URL%/}"
case "$PILOT_MANAGEMENT_URL" in
https://*) ;;
*) echo "Error: --managed-url must be an HTTPS origin." >&2; exit 2 ;;
esac
_managed_host="${PILOT_MANAGEMENT_URL#https://}"
case "$_managed_host" in
""|*/*|*@*|*\?*|*\#*)
echo "Error: --managed-url must not contain credentials, a path, query, or fragment." >&2
exit 2 ;;
esac
validate_safe "management host" "$_managed_host" ".:-"
if [ -n "$PILOT_POSITIONAL" ]; then
echo "Error: --managed-url cannot be combined with an install/uninstall positional command." >&2
exit 2
fi
if [ -n "$PILOT_REQUESTED_VERSION" ] || [ -n "${PILOT_RELEASE_TAG:-}" ] \
|| [ -n "$PILOT_REQUESTED_CHANNEL" ] || [ "${PILOT_RC:-}" = "1" ]; then
echo "Error: managed adoption uses the runtime pinned by the management authority; do not combine it with --version or --channel." >&2
exit 2
fi
MANAGED_TOKEN="${PILOT_ENROLLMENT_TOKEN:-}"
# Do not let the bearer secret reach curl, tar, service managers, or any
# other child. It is exported only to the single pilotctl claim process.
unset PILOT_ENROLLMENT_TOKEN
if [ -e "$MANAGED_CONTROL_PATH" ]; then
if [ -L "$MANAGED_CONTROL_PATH" ] || [ ! -f "$MANAGED_CONTROL_PATH" ]; then
echo "Error: the existing managed control attachment is not a regular file." >&2
exit 1
fi
if [ -n "$MANAGED_TOKEN" ]; then
echo "Error: this node is already managed; refusing to consume a new enrollment token." >&2
echo " Re-run without PILOT_ENROLLMENT_TOKEN to repair or update the managed runtime." >&2
exit 1
fi
else
if [ -z "$MANAGED_TOKEN" ]; then
echo "Error: PILOT_ENROLLMENT_TOKEN is required for first managed adoption." >&2
exit 1
fi
_managed_token_bytes=$(printf '%s' "$MANAGED_TOKEN" | wc -c | tr -d ' ')
if [ "$_managed_token_bytes" -gt 4096 ] \
|| LC_ALL=C printf '%s' "$MANAGED_TOKEN" | grep -q '[[:cntrl:]]'; then
echo "Error: PILOT_ENROLLMENT_TOKEN is invalid." >&2
exit 1
fi
fi
# Managed credentials and state created by this process default owner-only.
umask 077
MANIFEST_URL="${PILOT_MANAGEMENT_URL}/.well-known/pilot-managed-runtime.json"
elif [ "$PILOT_MANAGED_NO_START" = "1" ]; then
echo "Error: --no-start is only valid with --managed-url." >&2
exit 2
fi
# Validate channel value early so we fail fast. `edge` is a back-compat alias
# for `beta`: the manifest publishes channels.stable and channels.beta only, so
# a literal `edge` lookup would resolve empty and (previously) silently fall
# through to an unverified source build. Normalise it to `beta` here.
if [ "$PILOT_REQUESTED_CHANNEL" = "edge" ]; then
PILOT_REQUESTED_CHANNEL="beta"
fi
if [ -n "$PILOT_REQUESTED_CHANNEL" ] \
&& [ "$PILOT_REQUESTED_CHANNEL" != "stable" ] \
&& [ "$PILOT_REQUESTED_CHANNEL" != "beta" ]; then
echo "Error: --channel must be 'stable' or 'beta' (got: $PILOT_REQUESTED_CHANNEL)" >&2
exit 2
fi
# Restore positional args so the existing uninstall handler still uses $1.
# shellcheck disable=SC2086 # intentional word-split on PILOT_POSITIONAL
set -- $PILOT_POSITIONAL
# Refuse to run as root — daemon must run as the invoking user so identity.json
# and received files land under that user's home, not /root.
if [ "${1:-}" != "uninstall" ] && [ "$(id -u)" = "0" ] && [ -z "${PILOT_ALLOW_ROOT:-}" ]; then
echo "Error: refusing to install as root."
echo " Run as a regular user; the installer uses sudo only when needed."
echo " Set PILOT_ALLOW_ROOT=1 to override (not recommended)."
exit 1
fi
# A managed identity is per node, but the CLI links, service label and daemon
# socket are machine-wide. A different HOME therefore does not make a second
# installation safe. Refuse before downloading, stopping services, replacing
# links or consuming the enrollment token. An existing attachment in this
# same PILOT_DIR remains the ordinary repair/update path handled above.
if [ "$PILOT_MANAGED_MODE" = "1" ] && [ ! -e "$MANAGED_CONTROL_PATH" ] \
&& [ "${PILOT_REPLACE_EXISTING_NODE:-}" != "1" ]; then
_pilot_collision=""
for _pilot_link in /usr/local/bin/pilotctl /usr/local/bin/pilot-daemon; do
if [ -L "$_pilot_link" ]; then
_pilot_target=$(readlink "$_pilot_link" 2>/dev/null || true)
case "$_pilot_target" in
"$BIN_DIR"/*) ;;
*/.pilot/bin/*) _pilot_collision="${_pilot_collision}${_pilot_collision:+, }$_pilot_link -> $_pilot_target" ;;
esac
fi
done
_pilot_os=$(uname -s | tr '[:upper:]' '[:lower:]')
if [ "$_pilot_os" = "darwin" ] && command -v launchctl >/dev/null 2>&1; then
_pilot_service=$(launchctl print "gui/$(id -u)/network.pilotprotocol.pilot-daemon" 2>/dev/null || true)
if [ -n "$_pilot_service" ] && ! printf '%s\n' "$_pilot_service" | grep -Fq "$BIN_DIR/pilot-daemon"; then
_pilot_collision="${_pilot_collision}${_pilot_collision:+, }LaunchAgent network.pilotprotocol.pilot-daemon"
fi
elif [ "$_pilot_os" = "linux" ] && command -v systemctl >/dev/null 2>&1; then
_pilot_service=$(systemctl cat pilot-daemon 2>/dev/null || true)
if [ -n "$_pilot_service" ] && ! printf '%s\n' "$_pilot_service" | grep -Fq "$BIN_DIR/pilot-daemon"; then
_pilot_collision="${_pilot_collision}${_pilot_collision:+, }systemd pilot-daemon"
fi
fi
if [ -n "$_pilot_collision" ]; then
MANAGED_TOKEN=""
unset MANAGED_TOKEN
echo "Error: another Pilot node installation already owns machine-wide resources." >&2
echo " Detected: $_pilot_collision" >&2
echo " This enrollment token was not consumed and nothing was changed." >&2
echo " Manage or remove the existing node first; do not run two node identities under one service label." >&2
exit 1
fi
_pilot_collision=""; _pilot_target=""; _pilot_service=""; _pilot_os=""
fi
# --- Manifest + version helpers ---
# fetch_manifest writes the manifest JSON to $1 and returns 0 on success.
# Soft-fails (returns 1) so callers fall back to the GitHub-redirect path
# when the manifest host is unreachable.
fetch_manifest() {
curl -fsSL --max-time 10 "$MANIFEST_URL" -o "$1" 2>/dev/null
}
# manifest_field "<path>" "<file>" extracts a string field. Supports nested
# paths like "channels.stable" with a one-level sed slice — POSIX shell only,
# no jq dependency. Returns empty if the field is absent.
manifest_field() {
_mf_field="$1"; _mf_file="$2"
case "$_mf_field" in
*.*)
_mf_outer="${_mf_field%%.*}"
_mf_inner="${_mf_field#*.}"
sed -n "/\"${_mf_outer}\"[[:space:]]*:[[:space:]]*{/,/^[[:space:]]*}/p" "$_mf_file" \
| grep "\"${_mf_inner}\"" | head -1 \
| sed -E "s/.*\"${_mf_inner}\"[[:space:]]*:[[:space:]]*\"([^\"]*)\".*/\\1/"
;;
*)
grep "\"${_mf_field}\"" "$_mf_file" | head -1 \
| sed -E "s/.*\"${_mf_field}\"[[:space:]]*:[[:space:]]*\"([^\"]*)\".*/\\1/"
;;
esac
}
# manifest_platform_sha256 "<os>-<arch>" "<file>" extracts the per-platform
# sha256 from the manifest's "platforms" map, e.g. the hash inside
# "platforms": { "darwin-arm64": { "url": "...", "sha256": "abc..." } }
# Returns empty if the platform block or its sha256 is absent. This is a second,
# independent integrity anchor (served from pilotprotocol.network) alongside the
# release's checksums.txt (served from GitHub).
manifest_platform_sha256() {
_mp_plat="$1"; _mp_file="$2"
# The authority is free to emit compact JSON. A line-range parser sees all
# platform objects on that one line and a greedy replacement can therefore
# return the final platform's hash. Collapse whitespace deliberately, then
# constrain the match to this platform's first closing brace.
tr -d '\r\n' < "$_mp_file" \
| sed -n -E "s/.*\"${_mp_plat}\"[[:space:]]*:[[:space:]]*\\{[^}]*\"sha256\"[[:space:]]*:[[:space:]]*\"([^\"]*)\"[^}]*\\}.*/\\1/p" \
| head -1
}
# version_compare a b emits -1 / 0 / 1 for a<b / a==b / a>b.
# Honors semver: a prerelease tag ("X.Y.Z-rcN") is LOWER than the same base
# without it ("X.Y.Z"). Plain `sort -V` gets this backwards on hyphenated
# suffixes, so we split on "-" and compare the base versions first, then
# break ties on the prerelease suffix.
version_compare() {
_vc_a="${1#v}"; _vc_b="${2#v}"
if [ "$_vc_a" = "$_vc_b" ]; then echo 0; return; fi
_vc_a_base="${_vc_a%%-*}"; _vc_b_base="${_vc_b%%-*}"
if [ "$_vc_a_base" = "$_vc_b_base" ]; then
_vc_a_pre=0; case "$_vc_a" in *-*) _vc_a_pre=1 ;; esac
_vc_b_pre=0; case "$_vc_b" in *-*) _vc_b_pre=1 ;; esac
if [ "$_vc_a_pre" = "1" ] && [ "$_vc_b_pre" = "0" ]; then printf '%s\n' -1; return; fi
if [ "$_vc_a_pre" = "0" ] && [ "$_vc_b_pre" = "1" ]; then echo 1; return; fi
_vc_a_suf="${_vc_a#*-}"; _vc_b_suf="${_vc_b#*-}"
_vc_older=$(printf '%s\n%s\n' "$_vc_a_suf" "$_vc_b_suf" | sort -V | head -1)
if [ "$_vc_older" = "$_vc_a_suf" ]; then printf '%s\n' -1; else echo 1; fi
return
fi
_vc_older=$(printf '%s\n%s\n' "$_vc_a_base" "$_vc_b_base" | sort -V | head -1)
if [ "$_vc_older" = "$_vc_a_base" ]; then printf '%s\n' -1; else echo 1; fi
}
# --- Uninstall ---
if [ "${1}" = "uninstall" ]; then
echo ""
echo " Uninstalling Pilot Protocol..."
echo ""
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
# Stop daemon
if [ -x "$BIN_DIR/pilotctl" ]; then
"$BIN_DIR/pilotctl" daemon stop 2>/dev/null || true
# Gateway is extras-only in the core CLI: plain `pilotctl gateway stop`
# hard-errors ("gateway commands are not in the core CLI"), so the
# gateway was never actually stopped on uninstall.
"$BIN_DIR/pilotctl" extras gateway stop 2>/dev/null || true
elif command -v pilotctl >/dev/null 2>&1; then
pilotctl daemon stop 2>/dev/null || true
pilotctl extras gateway stop 2>/dev/null || true
fi
# Remove the /usr/local/bin symlinks the installer creates. Without this a
# dangling `pilotctl` stays on the default PATH after uninstall and fails
# with a confusing "No such file or directory". Only ever unlinks a SYMLINK
# that actually points into this user's ~/.pilot/bin — an unrelated real
# file of the same name is left alone. Same `sudo -n` gate as install: no
# password prompt, skip silently when we cannot write.
UNLINK_DIR="/usr/local/bin"
UNLINK_SUDO=""
if [ ! -w "$UNLINK_DIR" ] && sudo -n true 2>/dev/null; then
UNLINK_SUDO="sudo"
fi
for _b in pilotctl pilot-daemon pilot-gateway pilot-updater; do
if [ -L "$UNLINK_DIR/$_b" ]; then
case "$(readlink "$UNLINK_DIR/$_b" 2>/dev/null)" in
"$BIN_DIR"/*)
# shellcheck disable=SC2086 # "" or "sudo" — intentional split
if $UNLINK_SUDO rm -f "$UNLINK_DIR/$_b" 2>/dev/null; then
echo " Removed ${UNLINK_DIR}/${_b}"
fi
;;
esac
fi
done
# Remove system services (daemon + updater)
if [ "$OS" = "linux" ]; then
if [ "$(id -u)" = "0" ] || sudo -n true 2>/dev/null; then
for svc in pilot-daemon pilot-updater; do
if [ -f "/etc/systemd/system/${svc}.service" ]; then
sudo systemctl stop "$svc" 2>/dev/null || true
sudo systemctl disable "$svc" 2>/dev/null || true
sudo rm -f "/etc/systemd/system/${svc}.service"
fi
done
# Never let daemon-reload abort the uninstall under `set -e`: on a
# host with sudo but no systemd (container / WSL / CI) systemctl is
# missing or fails, and the abort left ~/.pilot in place after the
# user asked to uninstall. Matches the install-side handling below.
sudo systemctl daemon-reload 2>/dev/null || true
echo " Removed systemd services"
else
echo " Skipped systemd removal (run with sudo to remove)"
fi
fi
if [ "$OS" = "darwin" ]; then
# New labels + legacy labels (migration cleanup from earlier installs)
for label in network.pilotprotocol.pilot-daemon network.pilotprotocol.pilot-updater com.vulturelabs.pilot-daemon com.vulturelabs.pilot-updater; do
PLIST="$HOME/Library/LaunchAgents/${label}.plist"
if [ -f "$PLIST" ]; then
launchctl unload "$PLIST" 2>/dev/null || true
rm -f "$PLIST"
fi
done
echo " Removed LaunchAgents"
fi
# Remove pilot directory (binaries, config, identity, received files)
if [ -d "$PILOT_DIR" ]; then
rm -rf "$PILOT_DIR"
echo " Removed $PILOT_DIR"
fi
# Remove socket
rm -f /tmp/pilot.sock
echo ""
echo " Pilot Protocol uninstalled."
echo ""
exit 0
fi
# Detect platform
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)
case "$ARCH" in
x86_64) ARCH="amd64" ;;
aarch64) ARCH="arm64" ;;
arm64) ARCH="arm64" ;;
*) echo "Error: unsupported architecture: $ARCH"; exit 1 ;;
esac
case "$OS" in
linux|darwin) ;;
*) echo "Error: unsupported OS: $OS"; exit 1 ;;
esac
# --- Privilege helper ---
#
# Every privileged step (systemd units, service start/stop, /usr/local/bin
# symlinks) goes through this gate. It NEVER prompts: sudo is used only when
# `sudo -n` already succeeds without a password, and no prefix at all is used
# when we are already root — minimal containers frequently ship no sudo binary,
# so an unconditional `sudo systemctl ...` would fail there under PILOT_ALLOW_ROOT.
# CAN_PRIV says whether privileged steps can run at all.
PILOT_SUDO=""
CAN_PRIV=false
if [ "$(id -u)" = "0" ]; then
CAN_PRIV=true
elif sudo -n true 2>/dev/null; then
PILOT_SUDO="sudo"
CAN_PRIV=true
fi
echo ""
echo " Pilot Protocol"
echo " The network stack for AI agents."
echo ""
echo " Platform: ${OS}/${ARCH}"
echo " Registry: ${REGISTRY}"
echo " Beacon: ${BEACON}"
echo ""
# --- Resolve email ---
EMAIL="${PILOT_EMAIL:-}"
# Recover an email this host already has. account.json is written by the daemon,
# config.json by a previous run of this installer. Doing this on EVERY run — not
# just fresh installs — matters because the service unit is now regenerated on
# re-run: without it an upgrade would silently drop the address the operator
# configured at first install.
#
# Synthesised @nodes.pilotprotocol.network placeholders are deliberately NOT
# recovered. The daemon re-derives the identical value from the same identity
# key, so baking one into the unit adds nothing — and it would turn a soft
# default into a hard override that outranks the account file, silently
# defeating a later `pilotctl set-email`.
if [ -z "$EMAIL" ]; then
for _ef in "$PILOT_DIR/account.json" "$PILOT_DIR/config.json"; do
if [ -f "$_ef" ]; then
EMAIL=$(grep '"email"' "$_ef" 2>/dev/null | head -1 | cut -d'"' -f4 || true)
fi
case "$EMAIL" in
*@nodes.pilotprotocol.network) EMAIL="" ;;
esac
if [ -n "$EMAIL" ]; then
break
fi
done
fi
# On a fresh install with no email anywhere, ask for one — but only when there
# is a terminal to ask.
if [ -z "$EMAIL" ] && [ ! -x "$BIN_DIR/pilotctl" ]; then
# Interactive (TTY): prompt. Non-interactive (piped into a headless
# agent, no controlling terminal): do NOT block on /dev/tty — the
# daemon auto-synthesizes a <fingerprint>@nodes.pilotprotocol.network
# identity when email is empty, so a missing email must not abort.
if [ -t 0 ]; then
printf " Email (for account recovery): "
read -r EMAIL < /dev/tty
fi
if [ -z "$EMAIL" ]; then
if [ -t 0 ]; then
echo " Error: email is required. Set PILOT_EMAIL or enter when prompted."
exit 1
else
echo " Note: no email provided (non-interactive). Set PILOT_EMAIL= for account recovery."
fi
fi
fi
# The email is interpolated unquoted into config.json (a JSON string), the
# systemd unit ExecStart, and the launchd plist. Reject anything that could
# break out of those contexts (quotes, backslash, angle brackets, spaces,
# newlines). Standard email punctuation is allowed. Empty is fine here — an
# existing install without a new email keeps whatever it had.
if [ -n "$EMAIL" ]; then
validate_safe "email (PILOT_EMAIL)" "$EMAIL" "@.+_%-"
fi
# PILOT_HOSTNAME becomes a `-hostname <value>` argument in the root-owned
# systemd unit and the plist. A value with whitespace would inject additional
# daemon flags; validate it to hostname-safe characters.
if [ -n "${PILOT_HOSTNAME:-}" ]; then
validate_safe "hostname (PILOT_HOSTNAME)" "$PILOT_HOSTNAME" "._-"
fi
# --- Detect existing installation ---
UPDATING=false
if [ -x "$BIN_DIR/pilotctl" ]; then
UPDATING=true
CURRENT=$("$BIN_DIR/pilotctl" version 2>/dev/null || echo "unknown")
echo " Existing install detected (${CURRENT})"
echo " Updating binaries..."
echo ""
fi
# --- Download or build ---
TMPDIR=$(mktemp -d)
# Clean up both the download staging dir and any `<binary>.new.<pid>` file left
# behind by an interrupted atomic install (see install_bin below). The staging
# files live next to the real binaries so that rename(2) stays within one
# filesystem; they must never survive a failed run.
pilot_cleanup() {
rm -rf "$TMPDIR"
rm -f "$BIN_DIR"/*.new."$$" 2>/dev/null || true
}
trap pilot_cleanup EXIT
ARCHIVE="pilot-${OS}-${ARCH}.tar.gz"
# Resolve the release tag. Precedence (highest to lowest):
# 1. --version <tag> explicit pin via flag
# 2. PILOT_RELEASE_TAG env legacy explicit pin (back-compat)
# 3. --channel <name> manifest channel lookup
# 4. PILOT_RC=1 env legacy "beta" channel (back-compat)
# 5. Manifest "latest_stable" preferred for the default install
# 6. GitHub /releases/latest redirect — fallback when the manifest host
# is unreachable. Unauthenticated CDN, not subject to the 60/hr
# api.github.com rate limit.
MANIFEST_FILE="$TMPDIR/manifest.json"
HAVE_MANIFEST=0
if fetch_manifest "$MANIFEST_FILE"; then
HAVE_MANIFEST=1
fi
if [ "$PILOT_MANAGED_MODE" = "1" ] && [ "$HAVE_MANIFEST" != "1" ]; then
echo "Error: the management authority did not publish a managed-runtime manifest." >&2
echo " No binary or enrollment state was changed." >&2
exit 1
fi
if [ -n "$PILOT_REQUESTED_VERSION" ]; then
TAG="$PILOT_REQUESTED_VERSION"
elif [ -n "${PILOT_RELEASE_TAG:-}" ]; then
TAG="$PILOT_RELEASE_TAG"
elif [ -n "$PILOT_REQUESTED_CHANNEL" ] && [ "$HAVE_MANIFEST" = "1" ]; then
TAG=$(manifest_field "channels.${PILOT_REQUESTED_CHANNEL}" "$MANIFEST_FILE")
elif [ "${PILOT_RC:-}" = "1" ] && [ "$HAVE_MANIFEST" = "1" ]; then
TAG=$(manifest_field "channels.beta" "$MANIFEST_FILE")
elif [ "${PILOT_RC:-}" = "1" ]; then
# Manifest unreachable; fall back to api.github.com for the newest tag.
API_BODY="$TMPDIR/releases.json"
API_CODE=$(curl -sSL -o "$API_BODY" -w '%{http_code}' "https://api.github.com/repos/${REPO}/releases" 2>/dev/null || echo "000")
if [ "$API_CODE" = "403" ]; then
echo "Error: GitHub API rate-limited (403) while resolving the latest pre-release." >&2
echo " Workarounds:" >&2
echo " - retry in ~1 hour, OR" >&2
echo " - pin the tag: --version vX.Y.Z-rcN" >&2
echo " Refusing to silently source-build an unstamped binary." >&2
exit 1
fi
if [ "$API_CODE" = "200" ]; then
TAG=$(grep '"tag_name"' "$API_BODY" | head -1 | cut -d'"' -f4 || true)
fi
rm -f "$API_BODY"
elif [ "$HAVE_MANIFEST" = "1" ]; then
TAG=$(manifest_field "latest_stable" "$MANIFEST_FILE")
else
TAG=$(curl -fsSI "https://github.com/${REPO}/releases/latest/download/${ARCHIVE}" 2>/dev/null \
| grep -i '^location:' \
| sed -n 's|.*/releases/download/\([^/]*\)/.*|\1|p' \
| tr -d '\r' | head -1)
fi
if [ "$PILOT_MANAGED_MODE" = "1" ]; then
case "$TAG" in
managed-runtime-v[0-9]*.[0-9]*.[0-9]*) ;;
*)
echo "Error: the management authority published an invalid managed-runtime version." >&2
exit 1 ;;
esac
validate_safe "managed runtime version" "$TAG" ".-"
fi
# Fail loudly if the user explicitly asked for a released version/channel but it
# resolved to nothing. Silently dropping to the unpinned, UNVERIFIED source
# build below would give the user a binary they never asked for, with none of
# the provenance guarantees of a release. Only the fully-automatic default path
# (no explicit request) is allowed to fall back to a source build.
if [ -z "$TAG" ]; then
if [ -n "$PILOT_REQUESTED_VERSION" ]; then
echo "Error: requested version '$PILOT_REQUESTED_VERSION' could not be resolved to a release." >&2
exit 1
fi
if [ -n "${PILOT_RELEASE_TAG:-}" ]; then
echo "Error: PILOT_RELEASE_TAG='$PILOT_RELEASE_TAG' could not be resolved to a release." >&2
exit 1
fi
if [ -n "$PILOT_REQUESTED_CHANNEL" ]; then
echo "Error: channel '$PILOT_REQUESTED_CHANNEL' resolved to no release (manifest reachable: $HAVE_MANIFEST)." >&2
echo " Refusing to fall back to an unverified source build for an explicit channel request." >&2
exit 1
fi
if [ "${PILOT_RC:-}" = "1" ]; then
echo "Error: the beta/prerelease channel resolved to no release." >&2
echo " Refusing to fall back to an unverified source build for an explicit channel request." >&2
exit 1
fi
fi
# Warn when the resolved tag is older than the manifest's latest_stable.
# A confirmation prompt fires only when stdin is a TTY *and* --yes was not
# passed; non-interactive pipes (curl | sh) get the warning text without a
# prompt and proceed, so existing automation does not break.
if [ -n "$TAG" ] && [ "$HAVE_MANIFEST" = "1" ] && [ "$PILOT_NO_WARN" = "0" ]; then
LATEST_STABLE=$(manifest_field "latest_stable" "$MANIFEST_FILE")
if [ -n "$LATEST_STABLE" ] && [ "$TAG" != "$LATEST_STABLE" ]; then
CMP=$(version_compare "$TAG" "$LATEST_STABLE")
if [ "$CMP" = "-1" ]; then
echo "" >&2
echo "Warning: ${TAG} is older than the latest stable release (${LATEST_STABLE})." >&2
echo " Older versions miss security fixes. To install the latest stable," >&2
echo " re-run without --version, or pass --version ${LATEST_STABLE}." >&2
if [ "$PILOT_YES" != "1" ] && [ -t 0 ]; then
printf "Continue installing %s anyway? [y/N] " "$TAG" >&2
read -r _confirm
case "$_confirm" in
y|Y|yes|YES) ;;
*) echo "Aborted." >&2; exit 1 ;;
esac
fi
echo "" >&2
fi
fi
fi
if [ -n "$TAG" ]; then
URL="https://github.com/${REPO}/releases/download/${TAG}/${ARCHIVE}"
CHECKSUMS_URL="https://github.com/${REPO}/releases/download/${TAG}/checksums.txt"
echo "Downloading ${TAG}..."
if curl -fsSL "$URL" -o "$TMPDIR/$ARCHIVE" 2>/dev/null; then
# --- Verify SHA-256 (fail closed) ---
# This block NEVER extracts an archive it could not verify. Two
# independent anchors are used:
# EXPECTED_CKS — from the release's checksums.txt (GitHub)
# EXPECTED_MAN — the per-platform sha256 in the signed manifest
# (pilotprotocol.network)
# When both are present they must AGREE (defends against a compromise
# of either single source). At least one must be present, a working
# SHA-256 tool must exist, and the computed hash must match — otherwise
# the install aborts. (Previously a missing checksums.txt, a missing
# archive line, or the absence of shasum/sha256sum silently extracted
# the archive UNVERIFIED.)
EXPECTED_CKS=""
if curl -fsSL "$CHECKSUMS_URL" -o "$TMPDIR/checksums.txt" 2>/dev/null; then
EXPECTED_CKS=$(grep " ${ARCHIVE}\$" "$TMPDIR/checksums.txt" | awk '{print $1}')
fi
EXPECTED_MAN=""
if [ "$HAVE_MANIFEST" = "1" ]; then
EXPECTED_MAN=$(manifest_platform_sha256 "${OS}-${ARCH}" "$MANIFEST_FILE")
fi
# Cross-check the two anchors when both are available.
if [ -n "$EXPECTED_CKS" ] && [ -n "$EXPECTED_MAN" ] \
&& [ "$EXPECTED_CKS" != "$EXPECTED_MAN" ]; then
echo "Error: integrity anchors disagree for ${ARCHIVE}" >&2
echo " checksums.txt: $EXPECTED_CKS" >&2
echo " manifest: $EXPECTED_MAN" >&2
echo " Refusing to install." >&2
exit 1
fi
# Pick the expected hash (prefer checksums.txt; fall back to manifest).
EXPECTED="$EXPECTED_CKS"
[ -z "$EXPECTED" ] && EXPECTED="$EXPECTED_MAN"
if [ -z "$EXPECTED" ]; then
echo "Error: no SHA-256 available for ${ARCHIVE}." >&2
echo " checksums.txt was missing/incomplete and the manifest carried no hash." >&2
echo " Refusing to install an unverified binary." >&2
exit 1
fi
# Compute the actual hash; a missing tool is a hard failure, not a skip.
if command -v shasum >/dev/null 2>&1; then
ACTUAL=$(shasum -a 256 "$TMPDIR/$ARCHIVE" | awk '{print $1}')
elif command -v sha256sum >/dev/null 2>&1; then
ACTUAL=$(sha256sum "$TMPDIR/$ARCHIVE" | awk '{print $1}')
else
echo "Error: no SHA-256 tool (shasum or sha256sum) found." >&2
echo " Cannot verify ${ARCHIVE}; refusing to install unverified." >&2
echo " Install coreutils (sha256sum) or perl (shasum) and retry." >&2
exit 1
fi
if [ -z "$ACTUAL" ]; then
echo "Error: failed to compute SHA-256 of ${ARCHIVE}." >&2
exit 1
fi
if [ "$ACTUAL" != "$EXPECTED" ]; then
echo "Error: checksum mismatch for ${ARCHIVE}" >&2
echo " expected: $EXPECTED" >&2
echo " actual: $ACTUAL" >&2
exit 1
fi
if [ -n "$EXPECTED_CKS" ] && [ -n "$EXPECTED_MAN" ]; then
echo " Verified SHA-256 (checksums.txt + manifest)"
elif [ -n "$EXPECTED_CKS" ]; then
echo " Verified SHA-256 (checksums.txt)"
else
echo " Verified SHA-256 (manifest)"
fi
tar -xzf "$TMPDIR/$ARCHIVE" -C "$TMPDIR" --strip-components=1
else
if [ "$PILOT_MANAGED_MODE" = "1" ]; then
echo "Error: managed runtime ${TAG} could not be downloaded." >&2
echo " Refusing to fall back to an unmanaged build." >&2
exit 1
fi
# Archive download failed. Only the automatic default path may fall
# back to a source build; an explicit request already hard-failed
# above, so reaching here means no version/channel was pinned.
TAG=""
fi
fi
if [ -z "$TAG" ]; then
echo "No release available. Building from source..."
if ! command -v go >/dev/null 2>&1; then
echo "Error: Go is required to build from source."
echo "Install Go: https://go.dev/dl/"
exit 1
fi
if ! command -v git >/dev/null 2>&1; then
echo "Error: git is required to build from source."
exit 1
fi
echo "Cloning..."
git clone --depth 1 "https://github.com/${REPO}.git" "$TMPDIR/src" >/dev/null 2>&1
# Build from inside the cloned tree with GOWORK=off so a parent go.work
# in the user's $PWD does not reject the cloned module.
(
cd "$TMPDIR/src"
echo "Building daemon..."
GOWORK=off CGO_ENABLED=0 go build -o "$TMPDIR/pilot-daemon" ./cmd/daemon
echo "Building pilotctl..."
GOWORK=off CGO_ENABLED=0 go build -o "$TMPDIR/pilotctl" ./cmd/pilotctl
# gateway was extracted to a sibling repo (pilot-protocol/gateway)
# — only build from source when ./cmd/gateway still exists in this
# checkout. Release tarballs ship daemon/pilotctl/updater only.
if [ -d ./cmd/gateway ]; then
echo "Building gateway..."
GOWORK=off CGO_ENABLED=0 go build -o "$TMPDIR/pilot-gateway" ./cmd/gateway
fi
echo "Building updater..."
GOWORK=off CGO_ENABLED=0 go build -o "$TMPDIR/pilot-updater" ./cmd/updater
)
fi
# --- Install binaries to ~/.pilot/bin ---
echo "Installing binaries..."
mkdir -p "$BIN_DIR"
# Resolve every staged binary BEFORE touching the installed ones. Both naming
# conventions are accepted (release tarball: daemon/gateway; source build:
# pilot-daemon/pilot-gateway). If the payload is incomplete we abort here, with
# the existing install still fully intact — never half-way through a copy loop.
STAGED_DAEMON=""
if [ -f "$TMPDIR/daemon" ]; then
STAGED_DAEMON="$TMPDIR/daemon"
elif [ -f "$TMPDIR/pilot-daemon" ]; then
STAGED_DAEMON="$TMPDIR/pilot-daemon"
fi
STAGED_CTL=""
if [ -f "$TMPDIR/pilotctl" ]; then
STAGED_CTL="$TMPDIR/pilotctl"
fi
if [ -z "$STAGED_DAEMON" ] || [ -z "$STAGED_CTL" ]; then
echo "Error: the downloaded payload is missing pilot-daemon and/or pilotctl." >&2
echo " Nothing was replaced — your existing install is untouched." >&2
exit 1
fi
if [ "$PILOT_MANAGED_MODE" = "1" ]; then
_managed_probe=$(PILOT_ENROLLMENT_TOKEN='' "$STAGED_CTL" --json enterprise adopt --endpoint "$PILOT_MANAGEMENT_URL" 2>&1 || true)
case "$_managed_probe" in
*PILOT_ENROLLMENT_TOKEN*) ;;
*)
echo "Error: ${TAG} does not contain core managed-adoption support." >&2
echo " Nothing was replaced and the enrollment token was not consumed." >&2
exit 1 ;;
esac
_managed_probe=""
fi
# gateway is optional: extracted to a sibling repo, no longer ships in
# release tarballs (release.yml BINS=daemon/pilotctl/updater) and the
# source build only runs when ./cmd/gateway is present in the checkout.
STAGED_GATEWAY=""
if [ -f "$TMPDIR/gateway" ]; then
STAGED_GATEWAY="$TMPDIR/gateway"
elif [ -f "$TMPDIR/pilot-gateway" ]; then
STAGED_GATEWAY="$TMPDIR/pilot-gateway"
fi
STAGED_UPDATER=""
if [ -f "$TMPDIR/updater" ]; then
STAGED_UPDATER="$TMPDIR/updater"
elif [ -f "$TMPDIR/pilot-updater" ]; then
STAGED_UPDATER="$TMPDIR/pilot-updater"
fi
# --- Stop managed services before swapping binaries ---
#
# The installer now auto-enables and STARTS pilot-updater, so on any re-run
# (the advertised upgrade path) its binary is a live executable image. Two
# problems follow, and both are fixed here:
#
# 1. `cp` over a running executable fails with ETXTBSY ("Text file busy"),
# which under `set -e` aborted the whole re-run mid-install — binaries
# partially replaced, unit file never rewritten.
# 2. Even a successful swap does nothing until the process re-execs; the
# running service keeps the old image.
#
# We stop what is running, remember it, and restart it after the units have
# been regenerated. install_bin below independently defeats ETXTBSY via
# rename(2), which also covers daemons we do not manage (e.g. one started with
# `pilotctl daemon start` on a systemd-less host).
RESTART_SYSTEMD=""
RESTART_LAUNCHD=""
if [ "$OS" = "linux" ] && [ "$CAN_PRIV" = true ] \
&& command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then
for _svc in pilot-daemon pilot-updater; do
_state=$(systemctl is-active "$_svc" 2>/dev/null || true)
_want=""
case "$_state" in
active|activating|reloading)
_want=1 ;;
failed)
# A unit crashlooping on a bad ExecStart — exactly what the
# empty `-email` produced — alternates between activating and
# failed. Repairing its unit has to bring it back up, so an
# ENABLED failed unit counts as "should be running" too. A unit
# the operator deliberately disabled is left alone.
if systemctl is-enabled --quiet "$_svc" 2>/dev/null; then
_want=1
fi ;;
esac
if [ -n "$_want" ]; then
if { [ "$PILOT_MANAGED_MODE" != "1" ] || [ "$PILOT_MANAGED_NO_START" != "1" ]; } \
&& { [ "$PILOT_MANAGED_MODE" != "1" ] || [ "$_svc" != "pilot-updater" ]; }; then
RESTART_SYSTEMD="${RESTART_SYSTEMD}${RESTART_SYSTEMD:+ }${_svc}"
fi
# shellcheck disable=SC2086 # $PILOT_SUDO is "" or "sudo" — intentional split
$PILOT_SUDO systemctl stop "$_svc" 2>/dev/null || true
echo " Stopped ${_svc} (will restart after upgrade)"
fi
done
fi
if [ "$OS" = "darwin" ]; then
for _label in network.pilotprotocol.pilot-daemon network.pilotprotocol.pilot-updater; do
_lp="$HOME/Library/LaunchAgents/${_label}.plist"
if [ -f "$_lp" ] && launchctl list 2>/dev/null | grep -q "$_label"; then
if { [ "$PILOT_MANAGED_MODE" != "1" ] || [ "$PILOT_MANAGED_NO_START" != "1" ]; } \
&& { [ "$PILOT_MANAGED_MODE" != "1" ] || [ "$_label" != "network.pilotprotocol.pilot-updater" ]; }; then
RESTART_LAUNCHD="${RESTART_LAUNCHD}${RESTART_LAUNCHD:+ }${_label}"
fi
launchctl unload "$_lp" 2>/dev/null || true
echo " Unloaded ${_label} (will reload after upgrade)"
fi
done
fi
# install_bin SRC DEST — put SRC at DEST atomically.
#
# Writes to a temp file in the SAME directory (so rename(2) never crosses a
# filesystem) and renames it into place. Renaming over a busy executable is
# always allowed: the old inode is simply unlinked and any process still
# running it keeps its own copy. That makes this immune to ETXTBSY and means a
# failure part-way through can never leave a truncated binary at the real path.
install_bin() {
_ib_tmp="${2}.new.$$"
cp "$1" "$_ib_tmp"
chmod 755 "$_ib_tmp"
mv -f "$_ib_tmp" "$2"
}
install_bin "$STAGED_DAEMON" "$BIN_DIR/pilot-daemon"
install_bin "$STAGED_CTL" "$BIN_DIR/pilotctl"
[ -n "$STAGED_GATEWAY" ] && install_bin "$STAGED_GATEWAY" "$BIN_DIR/pilot-gateway"
[ -n "$STAGED_UPDATER" ] && install_bin "$STAGED_UPDATER" "$BIN_DIR/pilot-updater"
# --- Optional hosted adoption (core Pilot, not MCP) ---
#
# The one-time token is exposed only to this process. pilotctl validates the
# delegated key, root pin, trust bundle, bootstrap policy, authority origins,
# and owner-only output before atomically installing ~/.pilot/managed.
MANAGED_ADOPTED=0
if [ "$PILOT_MANAGED_MODE" = "1" ] && [ ! -e "$MANAGED_CONTROL_PATH" ]; then
if ! _managed_result=$(PILOT_ENROLLMENT_TOKEN="$MANAGED_TOKEN" "$BIN_DIR/pilotctl" --json enterprise adopt --endpoint "$PILOT_MANAGEMENT_URL" 2>&1); then
MANAGED_TOKEN=""
unset MANAGED_TOKEN
echo "Error: the hosted authority did not complete managed adoption." >&2
printf '%s\n' "$_managed_result" >&2
exit 1
fi
MANAGED_TOKEN=""
unset MANAGED_TOKEN
_managed_result=""