Repository navigation
Expand file tree
/
Copy pathinstall-rust.sh
More file actions
executable file
·3352 lines (3274 loc) · 161 KB
/
Copy pathinstall-rust.sh
File metadata and controls
executable file
·3352 lines (3274 loc) · 161 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
# install-rust.sh — one-command installer for the Rust build of Prime Agent.
#
# THE KEYWORD TAKEOVER: the Rust port installs under the product keyword
# PRIME-AGENT — the launcher lands at ~/.local/bin/prime-agent, the payload
# at ~/.local/share/prime-agent/, and users type `prime-agent`. The old
# prime-agent-rust layout (a TS-safe side-by-side name) is migrated: the
# share tree moves to the new name with a one-generation .old rollback, and
# this script's own launcher replaces the prime-agent-rust one it wrote in
# past installs. The FILENAME stays install-rust.sh deliberately: the
# curl|sh URL and the update entry points (`prime-agent update`, the TUI
# /update — both run this script with no arguments) already point at it, and
# the filename is invisible to users; the command they type is what
# changed.
#
# SOURCE: the R2-backed release channel (this repo file is the source the
# release workflow uploads to the bucket as install.sh / install-beta.sh;
# the channel pointers and manifests it reads - latest.json / beta.json,
# the tarballs, SHA256SUMS - all come from the same download base). The
# workflow-artifact bootstrap channel is retired; the user path never
# touches GitHub.
#
# THE TYPESCRIPT TAKEOVER (this script is also the uninstall path for the
# TS product — one installer owns the keyword's lifecycle):
# 1. BOTH DAEMONS ARE STOPPED CLEANLY, NEVER KILLED (--force alone may
# signal one that will not stop), but only AFTER the new payload and
# launcher are published — the retirement steps (daemon stops, npm
# uninstall) never leave the machine without a
# working prime-agent if the install aborts mid-way. The probed
# candidates: the TS daemon's default socket
# (${TMPDIR:-/tmp}/prime-agent-$(id -u)/daemon.sock),
# PRIME_AGENT_DAEMON_SOCKET when a profile exported it (the
# non-default socket the first field install had), and this
# product's own pinned rust socket. The daemon that answers a
# candidate is classified by IDENTITY first — a hello whose
# runtime build id is this product's ("pa-daemon-rs-<version>",
# carried since the port) is OUR daemon of any build (the update
# flow: the running daemon holds the old binary and venv state, the
# update needs it down, the next invocation boots the new daemon —
# the summary's next-step line says so) — then by the protocol-7
# SCHEMA FAMILY: the family prefix minus this product's own hash is
# the TypeScript daemon of ANY version (the second field install
# answered schema-30-f908f493c9e1 where the last-known id was
# schema-29-a5c9d20f8b13; an exact-hash check left it running); the
# pinned rust socket is ours by construction, no classification at
# all (an installer older than the daemon build must still stop
# it). THE SELF-SOCKET REFUSAL: a candidate that equals the daemon
# DRIVING this very install (the internal supervisor-socket
# variable a daemon exports to its workers) is never probed at all
# — the suite that killed the fleet daemon twice ran exactly that
# shape — unless PRIME_AGENT_STOP_LIVE_DAEMON=1 overrides for a
# deliberate in-daemon update (--force does not); an operator shell
# never carries the internal variable, so the field contract is
# unchanged.
# Every daemon so identified is shut down REGARDLESS of busy-ness (the
# field ruling: an install that leaves the old daemon up is the
# takeover bug), by an ESCALATING ladder that sends no signal to any
# pid without --force: the graceful `shutdown` request (force:false), a 5s
# confirm poll, then the forced request (force:true) and a
# DRAIN-SCALED second poll (2s per reported session over a 5s
# floor — the field measured a 46-worker drain at ~49s, and a fixed
# 5s poll reported the dying daemon as a stop-failure) — every
# request is the daemon's own shutdown over its socket, and the
# sessions' state stays on disk for the Rust side. The install then
# VERIFIES every stopped socket is down (the socket stops
# answering) and reports what was stopped in the summary; a daemon
# that would not go down — or answers an unrecognized schema, or
# will not greet — is a LOUD warning naming it and the manual stop
# command (never a silent nothing-was-done), and a machine with no
# daemon anywhere says so (every candidate is reported — no silent
# skips). An unreadable session count never skips the stop.
# 2. THE TS FILES ARE PRESERVED, NOT DELETED (the pi_agent_rust
# `legacy-pi` precedent: rollback stays possible). What the TS
# installer actually created, researched from its install.sh: a
# managed root at ${XDG_DATA_HOME:-~/.local/share}/prime-agent
# (marked by .managed = prime-agent-native-v1, holding releases/<v>/
# trees and its own bin/prime-agent symlink), a public
# ~/.local/bin/prime-agent symlink into it, an optional global npm
# package, and an optional standalone node at
# ~/.local/share/prime-agent-node. The takeover:
# - a TS managed root occupying THIS script's target
# ($PREFIX/share/prime-agent) moves to
# $PREFIX/share/prime-agent-legacy (kept verbatim; rollback =
# rename back and re-link the public bin symlink);
# - the public ~/.local/bin/prime-agent is REPLACED by this
# script's launcher (the keyword is ours now);
# - the TS npm package is uninstalled (exact package `prime-agent`
# only; the restore command is printed with the recorded version);
# - the standalone node dir is LEFT in place (it is a runtime, not
# the product binary/package — the user can remove it by hand).
# 3. WHY DAEMON CONFLICTS ARE GONE AFTER THIS INSTALL: the launcher
# pins a rust-only daemon socket
# (${TMPDIR:-/tmp}/prime-agent-rust-$(id -u)/daemon.sock) — a
# different path than the TS daemon's own — so BY DEFAULT this CLI
# and the TS daemon never meet (each product's default socket is its
# own), and the install-time stop-when-idle above retires a TS daemon
# cleanly instead of orphaning one. Explicit overrides can still point
# anywhere (--daemon-socket > PRIME_AGENT_DAEMON_SOCKET > the pinned
# default — the product's documented contract; a foreign-schema daemon
# behind an override reads as stale, the same behavior in both
# products). Default pin + clean stop: out of the box, the two
# daemons cannot fight over a socket after install.
# Together with the kernel pre-warm below (uv + the Python venv at
# install time), a fresh install's FIRST session works out of the
# box, online or offline.
#
# THE SHARED STORE IS NEVER TOUCHED: ~/.prime/agent/ (sessions, leases,
# config) is read and written by BOTH products by design — the same
# sessions appear in either — and this installer never creates, renames,
# migrates, or deletes anything under it. guard_preserved() aborts the
# install if any computed path (prefix, bin, share, stage, rollback)
# falls under the store.
#
# Config (env with defaults):
# PRIME_AGENT_DOWNLOAD_BASE_URL the R2-backed download base (default:
# the official domain, the same base the
# release pipeline renders into the
# published copy of this script)
# PRIME_AGENT_RELEASE_CHANNEL stable | beta (default: stable)
# PRIME_AGENT_VERSION pin an exact version instead of reading
# the channel pointer
# PRIME_AGENT_RUST_PREFIX install prefix (default: ~/.local; the
# launcher lands at $PREFIX/bin/prime-agent,
# the payload at $PREFIX/share/prime-agent/)
# PRIME_AGENT_UV_BIN_DIR uv install dir (default: ~/.local/bin)
#
# THE CHANNEL (the R2 form, the TS install.sh parity): the script reads
# the channel pointer (<base>/stable or <base>/beta) for the version,
# reads the channel manifest (<base>/latest.json or <base>/beta.json) for
# this platform's artifact row, fetches the tarball + SHA256SUMS from
# <base>/releases/v<version>/, and verifies the checksum before
# extraction. NO GITHUB SURFACE anywhere in the user path: no gh, no
# GITHUB_TOKEN, no workflow-artifact API — the download base is the
# R2-backed domain, and everything the installer reads comes from it.
#
# Usage: install-rust.sh [--update] — both entry points install the
# channel's current version; the script is idempotent (a re-run replaces
# the payload, keeps one .old rollback generation, and re-runs the
# takeover steps as no-ops when there is nothing left to take over).
# install-rust.sh --rollback republishes that kept generation, and
# install-rust.sh --archive <path> publishes a local release archive
# instead of a channel download (`prime-agent update --rollback` and
# `--archive` run the copy of this script bundled into the binary).
#
# PREREQUISITES: curl + sh (+ the network for the download). The installer
# needs a Python for its own scripting steps (the store guard's realpath,
# the channel manifest's JSON parsing, the daemon probe) — but it does
# NOT need one installed: it bootstraps uv first (a static binary whose
# installer needs only curl + sh) and resolves its Python THROUGH uv (an
# existing interpreter when there is one, else uv's own managed 3.11 —
# no system python3 anywhere). Offline without uv, a system python3 is
# the fallback; with neither, the installer names the one missing
# prerequisite and exits.
set -eu
# The publish-rendered defaults: the release pipeline copies this script
# to <base>/install.sh with DOWNLOAD_BASE_URL_DEFAULT set to
# vars.R2_PUBLIC_BASE_URL, and to <base>/install-beta.sh with the channel
# default set to beta — the repo-file default IS the official domain, so
# the raw repo copy installs out of the box too.
DOWNLOAD_BASE_URL_DEFAULT="https://pub-728493de92a943e2a9b2d17b4719f318.r2.dev"
RELEASE_CHANNEL_DEFAULT="stable"
BASE_URL="${PRIME_AGENT_DOWNLOAD_BASE_URL:-$DOWNLOAD_BASE_URL_DEFAULT}"
CHANNEL="${PRIME_AGENT_RELEASE_CHANNEL:-$RELEASE_CHANNEL_DEFAULT}"
PREFIX="${PRIME_AGENT_RUST_PREFIX:-$HOME/.local}"
die() { echo "install-rust.sh: $1" >&2; exit 1; }
usage() {
cat <<'USAGE'
install-rust.sh — install the Rust build of Prime Agent under the prime-agent keyword.
The launcher lands at $PRIME_AGENT_RUST_PREFIX/bin/prime-agent and the payload at
$PRIME_AGENT_RUST_PREFIX/share/prime-agent/ (default prefix ~/.local). The installed
TypeScript product is taken over: its daemon is stopped with its own shutdown request,
its native install is preserved under share/prime-agent-legacy, and its npm package is
uninstalled (the restore command is printed). ~/.prime/agent (the shared session store)
is never touched. Both the default and --update install the channel's current version.
Needs curl + sh (+ the network): the installer bootstraps its own Python via
uv — no system python3 required. It also pre-warms the Python kernel (uv +
`prime-agent --prime-agent-bootstrap`); offline, that step degrades to a
warning and the first session bootstraps the kernel itself — it needs the
network once.
Options:
--update accepted alias; identical to a plain run
--force if a Prime Agent daemon (TypeScript or Rust) is still up after the
shutdown requests and the drain wait, send it SIGTERM, then SIGKILL.
Never applies to the daemon this install runs under.
(from a pipe: curl -fsSL <url>/install.sh | sh -s -- --force)
--verbose the detail also goes to stdout, not just fd 3 (no animation)
--rollback restore the previous version the last install kept
(share/prime-agent.old.*); the replaced version is kept in
its place, so a second --rollback undoes the first
--archive <path>
install a local prime-agent-<version>-<platform>.tar.gz
release archive instead of downloading from the channel
Output:
stderr the title, one line per step, warnings with the command that
fixes them, and the ending; on a terminal an animated banner,
a spinner, and a download bar (NO_COLOR or TERM=dumb: plain)
stdout nothing by default; --verbose prints the detail here
fd 3 the detail — a wrapper captures it by opening fd 3; a bare run
leaves it closed
Environment:
PRIME_AGENT_DOWNLOAD_BASE_URL the R2-backed download base (the official
domain by default)
PRIME_AGENT_RELEASE_CHANNEL stable | beta (stable by default)
PRIME_AGENT_VERSION pin an exact version (skips the channel
pointer read; the manifest + SHA256SUMS
checks still run)
PRIME_AGENT_RUST_PREFIX install prefix (~/.local by default)
PRIME_AGENT_UV_BIN_DIR uv install dir (~/.local/bin by default)
PRIME_AGENT_RUST_VERBOSE 1 = the --verbose output mode
PRIME_AGENT_ROLLBACK_CHECK 1 = with --rollback, print the resolved
rollback source and exit without touching
the payload (the update command's
synchronous pre-flight)
PRIME_AGENT_ARCHIVE_CHECK 1 = with --archive, validate the archive
(its name, tar, payload, and version) and
exit without publishing (the same
pre-flight for the archive route)
USAGE
}
# --- arguments ---------------------------------------------------------------
# No positional arguments. --update is an accepted alias identical to the
# default run (the update entry points, `prime-agent update` and the TUI
# /update, run this script with no arguments) because the flow is idempotent
# by construction. --verbose folds the fd-3 progress detail onto stdout
# (PRIME_AGENT_RUST_VERBOSE=1 does the same).
# --rollback and --archive pick the payload source (MODE); the default is the
# channel download.
VERBOSE="${PRIME_AGENT_RUST_VERBOSE:-0}"
FORCE=0
MODE="channel"
ARCHIVE=""
# THE TRUSTED TASKLIST: the liveness question goes to Windows's own
# tasklist, never through the inherited PATH — this script runs with the
# updater's environment (the funnel's own shell is trusted-rooted for
# exactly that reason), and a repo- or user-planted lookup would run
# BEFORE the publish with the credentials that hardening guards.
# System32 alone answers: the machine's own SystemRoot spelling first,
# the MSYS C: mount second. A machine offering neither (every unix; a
# stripped Windows env) simply has no answerable liveness question, and
# both callers treat the empty TASKLIST as "cannot ask" — the parent wait
# proceeds, the publication lock refuses with its manual-recovery
# message instead of trusting a miss.
TASKLIST=""
if [ -n "${SystemRoot:-}" ] && [ -x "${SystemRoot}/System32/tasklist.exe" ]; then
TASKLIST="${SystemRoot}/System32/tasklist.exe"
elif [ -x /c/Windows/System32/tasklist.exe ]; then
TASKLIST=/c/Windows/System32/tasklist.exe
fi
# THE HANDOFF PARENT WAIT: the Windows update command spawns THIS script
# and exits precisely so its own payload image stops locking
# <prefix>/share/prime-agent for the publish below — but a fast child
# could reach that rename while the parent still lives. The handoff sets
# the parent's pid here; the payload touch happens many steps below, and
# this bounded wait (the parent is normally gone in milliseconds) makes
# the release-before-publish ordering explicit instead of incidental.
# tasklist carries the liveness question to Windows the same way the
# publication lock does (the MSYS kill cannot see a native pid).
if [ -n "${PRIME_AGENT_INSTALLER_PARENT_PID:-}" ] && [ -n "$TASKLIST" ]; then
parent_waits=0
while MSYS2_ARG_CONV_EXCL='*' "$TASKLIST" \
/FI "PID eq ${PRIME_AGENT_INSTALLER_PARENT_PID}" 2>/dev/null \
| grep -qw "${PRIME_AGENT_INSTALLER_PARENT_PID}"; do
parent_waits=$((parent_waits + 1))
[ "$parent_waits" -gt 300 ] && die "the prime-agent process that started this installer (pid ${PRIME_AGENT_INSTALLER_PARENT_PID}) is still running after 30s; the payload it holds cannot be replaced while it lives — stop that process and re-run"
sleep 0.1 2>/dev/null || sleep 1
done
fi
# Every argument is scanned (no positionals exist): the flags compose, so
# `--update --verbose` sets both effects instead of silently dropping one.
while [ $# -gt 0 ]; do
case "$1" in
--update) ;;
--rollback)
[ "$MODE" = archive ] && die "--rollback and --archive are exclusive"
MODE="rollback" ;;
--archive)
[ "$MODE" = rollback ] && die "--rollback and --archive are exclusive"
[ $# -ge 2 ] || { usage >&2; die "--archive needs the path of a release archive"; }
MODE="archive"
ARCHIVE="$2"
shift ;;
--verbose|-v) VERBOSE=1 ;;
--force) FORCE=1 ;;
-h|--help) usage; exit 0 ;;
*) usage >&2; die "unknown argument: $1" ;;
esac
shift
done
# --- the output contract ------------------------------------------------------
# Everything a person reads goes to stderr, kept short: a title, one line
# per step that did something ("✓ Installed"), warnings with the exact
# command that fixes them, and a short ending. On a terminal one renderer
# owns the screen while the install runs: an awk loop (below) that draws
# the TUI's animated brand mark, the title, the finished steps, and the
# active step's spinner (and the download bar), rewriting only the rows
# that changed each 120ms tick; it freezes on its last frame when the
# install ends. The install itself only writes the step state to files the
# renderer reads. Captured output (CI, pipes, the TUI's /update) gets the
# same lines with no colors, no animation, and no carriage returns, and a
# failure's error stays the last stderr line (the update reports that
# tail). The extra detail rides fd 3: a wrapper captures it by opening
# fd 3, a bare run leaves it closed, and --verbose folds it onto stdout.
if [ "$VERBOSE" = 1 ]; then
exec 3>&1
elif ( : >&3 ) 2>/dev/null; then
: # already open — a wrapper's capture channel; keep it (the subshell
# probe tests the DESCRIPTOR, not a /dev/fd node: on macOS /dev/fd/3
# exists while fd 3 is closed, and a redirect onto a closed fd under
# set -e would abort the installer at its first progress line)
else
exec 3>/dev/null
fi
UI_TTY=0
if [ -t 2 ] && [ "${TERM:-}" != dumb ]; then UI_TTY=1; fi
# The renderer redraws rows in place, so it stays off when --verbose
# interleaves detail lines on the same terminal.
UI_ANIM=0
if [ "$UI_TTY" = 1 ] && [ "$VERBOSE" != 1 ]; then UI_ANIM=1; fi
UI_COLOR=0
if [ "$UI_TTY" = 1 ] && [ -z "${NO_COLOR:-}" ]; then UI_COLOR=1; fi
# The prime theme's palette (crates/pa-types/themes/prime.json), 24-bit.
C_BOLD="" C_DIM="" C_ACCENT="" C_WARN="" C_RESET=""
if [ "$UI_COLOR" = 1 ]; then
esc="$(printf '\033')"
C_BOLD="${esc}[1m"
C_DIM="${esc}[38;2;113;113;122m"
C_ACCENT="${esc}[38;2;124;111;175m"
C_WARN="${esc}[38;2;245;158;11m"
C_RESET="${esc}[0m"
fi
SAY_DIM="" SAY_RESET=""
if [ "$VERBOSE" = 1 ] && [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
SAY_DIM="$(printf '\033')[38;2;113;113;122m" SAY_RESET="$(printf '\033')[0m"
fi
say() { printf '%s%s%s\n' "$SAY_DIM" "$*" "$SAY_RESET" >&3; }
# The program text is awk, not shell: its "$PRIME_AGENT_UI_DIR" expands later.
# shellcheck disable=SC2016
banner_awk='# BANNER_AWK_BEGIN
# The installer banner: the TUI first-run splash (crates/pa-tui/src/
# onboarding.rs mark_rows + draw_field), ported cell for cell so the same
# frame at the same width draws the same canvas; the parity test in that
# file runs this program (-v parity=1) against the Rust renderer.
function remeu(a, m) { a = a % m; if (a < 0) a += m; return a }
function absv(a) { return a < 0 ? -a : a }
function put(x, y, ch, tone, pri, k) {
if (y < 0 || y >= MH || x < 0 || x >= W) return
k = y * W + x
if (CP[k] > pri) return
CC[k] = ch; CT[k] = tone; CP[k] = pri
}
function field(frame, x, y, k, hash, cx, cy, contour, hy, si, seg, t, base, wave, ty, i, n, parts, eq) {
for (k = 0; k < W * MH; k++) { CC[k] = " "; CT[k] = "D"; CP[k] = 0 }
cx = int(W * 36 / 100); cy = int(MH * 54 / 100); hy = int(MH * 58 / 100)
for (y = 0; y < MH; y++) for (x = 0; x < W; x++) {
hash = (x * 37 + y * 53 + frame * 11 + x * y * 3) % 101
if (hash < 3) put(x, y, "·", "D", 1)
contour = absv(x - cx) + absv(y - cy) * 4 + int(x / 6) - frame
if (x < int(W * 82 / 100) && remeu(contour, 24) == 12) put(x, y, ((x + y) % 5 == 0) ? "╌" : "·", "B", 2)
if (y == hy && x % 2 == 0 && (x + frame) % 13 < 2) put(x, y, "─", ((x + frame) % 3 == 0) ? "A" : "D", 3)
if (x >= QX0 && !(x <= QX1 && y <= MH - 1) && x % 4 == 0) {
si = int(x / 4); seg = (y + si * 2 + int(frame / 2)) % 6
if (y > 0 && y < MH - 1 && seg < 2) put(x, y, ((si + y) % 4 == 0) ? "┃" : "▎", "L", 4)
}
}
for (t = 0; t < 3; t++) {
base = (t == 0) ? int(MH * 30 / 100) : (t == 1) ? int(MH * 49 / 100) : int(MH * 72 / 100)
for (x = 0; x < W; x++) {
wave = (x * 2 + frame + t * 7) % 16
if (wave > 7) wave = 15 - wave
ty = base + int((wave - 3) / 2)
if (ty < 0) ty = 0
if ((x + frame + t * 13) % 41 == 0) put(x, ty, "◆", "W", 6)
else if ((x + frame) % 12 == 0) put(x, ty, "•", "A", 6)
else put(x, ty, "·", "A", 3)
}
}
for (y = 0; y < MH; y++) {
n = split(LOGO[y], parts, "|")
for (i = 1; i <= n; i++) {
eq = index(parts[i], "=")
put(LI + substr(parts[i], 1, eq - 1), y, substr(parts[i], eq + 1), "T", 8)
}
}
}
function mark_row(y, x, k, s, cur) {
s = ""; cur = ""
for (x = 0; x < W; x++) {
k = y * W + x
if (CT[k] != cur) { cur = CT[k]; s = s TONE[cur] }
s = s CC[k]
}
return s RESET
}
function mb(b) { return sprintf("%.1f MB", b / 1000000) }
# Move the cursor to region row i (row 0 is the line the renderer started
# on); rows past the bottom are created with newlines.
function go(i) {
if (i >= existing) {
go(existing - 1)
while (existing <= i) { printf "\n"; existing++; cur = existing - 1 }
return
}
if (i < cur) printf "%s[%dA", ESC, cur - i
else if (i > cur) printf "%s[%dB", ESC, i - cur
cur = i
}
function compose( n, line, label, detail, ppath, total, got, cmd, filled, bar, c) {
n = 0
if (banner == 1) {
field(frame)
R[n++] = ""
for (y = 0; y < MH; y++) R[n++] = mark_row(y)
R[n++] = ""
}
line = ""
if ((getline line < brandf) < 0) line = ""
close(brandf)
R[n++] = " " TX "Installing " BOLD "PRIME" RESET TX ITAL " Agent" RESET (line == "" ? "" : " " DIM line RESET)
R[n++] = ""
while ((getline line < logf) > 0) R[n++] = line
close(logf)
label = ""; detail = ""; ppath = ""; total = ""
if ((getline label < activef) > 0) {
getline detail < activef; getline ppath < activef; getline total < activef
}
close(activef)
if (label != "") {
if (ppath != "") {
# The path never enters the command text: the shell expands the
# environment variable itself (a TMPDIR with shell syntax stays data).
got = 0; cmd = "{ wc -c < \"$PRIME_AGENT_UI_DIR/ui-progress\"; } 2>/dev/null"
cmd | getline got; close(cmd); got += 0
if (total + 0 > 0) {
filled = int(got * 20 / total); if (filled > 20) filled = 20
bar = ""
for (c = 0; c < 20; c++) bar = bar (c < filled ? "█" : "░")
detail = AC bar RESET DIM " " mb(got) " / " mb(total) (detail == "" ? "" : " · " detail)
} else detail = mb(got) (detail == "" ? "" : " · " detail)
}
R[n++] = " " AC SPIN[frame % 10 + 1] RESET " " label (detail == "" ? "" : " " DIM detail RESET)
}
return n
}
function draw(n, i) {
for (i = 0; i < n; i++) {
if ((i in PREV) && PREV[i] == R[i]) continue
PREV[i] = R[i]
# A row scrolled off the top can no longer be reached: leave it.
if (i < existing - TH) continue
go(i); printf "\r%s[2K%s", ESC, R[i]
}
for (i = n; i < pn; i++) { if (i >= existing - TH) { go(i); printf "\r%s[2K", ESC }; delete PREV[i] }
pn = n
fflush()
}
BEGIN {
ESC = "\033"
MH = 7; LI = 5; QX0 = 5; QX1 = 26
LOGO[0] = "17=▗|18=▄|19=▄|20=█|21=▀"
LOGO[1] = "3=█|4=█|5=█|6=▄|14=▗|15=▄|16=█|17=█|18=█|19=▀"
LOGO[2] = "2=▗|3=█|4=▛|5=▐|6=█|7=▙|11=▗|12=▄|13=█|14=▀|15=▗|16=█|17=▀"
LOGO[3] = "1=▗|2=█|3=▛|5=▟|6=█|7=█|8=▙|9=▄|10=█|11=█|12=▛|14=▟|15=▛"
LOGO[4] = "1=▗|2=▟|3=▌|5=▐|6=█|7=█|8=█|9=▛|10=▘|11=▗|12=▄|13=█|14=▖"
LOGO[5] = "0=▟|1=█|2=█|3=█|4=▄|7=▄|8=▄|9=▟|10=█|11=█|12=█|13=▀"
LOGO[6] = "0=▜|1=█|2=▛|3=▀|4=▘|7=▜|8=█|9=▛|10=▀|11=▘"
if (color == 1) {
RESET = ESC "[0m"; BOLD = ESC "[1m"; ITAL = ESC "[3m"; TX = ESC "[39m"
DIM = ESC "[38;2;113;113;122m"; AC = ESC "[38;2;124;111;175m"
TONE["T"] = ESC "[39m"; TONE["D"] = DIM; TONE["B"] = ESC "[38;2;82;82;91m"
TONE["A"] = AC; TONE["L"] = ESC "[38;2;56;189;248m"; TONE["W"] = ESC "[38;2;245;158;11m"
}
W = width + 0
if (parity == 1) {
field(frame + 0)
for (y = 0; y < MH; y++) {
chars = ""; tones = ""
for (x = 0; x < W; x++) { chars = chars CC[y * W + x]; tones = tones CT[y * W + x] }
print chars "\t" tones
}
exit
}
split("⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏", SPIN, " ")
uidir = ENVIRON["PRIME_AGENT_UI_DIR"]
activef = uidir "/ui-active"; logf = uidir "/ui-log"; brandf = uidir "/ui-brand"; stopf = uidir "/ui-stop"
TH = height + 0; if (TH < 5) TH = 24
frame = 0; existing = 1; cur = 0; pn = 0
printf "%s[?25l%s[?7l", ESC, ESC
while (1) {
stopping = ((getline tmp < stopf) >= 0); close(stopf)
n = compose()
draw(n)
if (stopping) break
if (system("kill -0 " ppid " 2>/dev/null && { sleep 0.12 2>/dev/null || sleep 1; }") != 0) break
frame++
}
go(n - 1)
printf "\n%s[?7h%s[?25h", ESC, ESC
fflush()
}
# BANNER_AWK_END
'
dl="$(mktemp -d "${TMPDIR:-/tmp}/prime-agent-download.XXXXXX")"
# The renderer's inputs: the active step (label, detail, the file being
# downloaded, its size), the finished lines, the title's version text, and
# the stop flag. Warnings wait in ui_notes and print in full once the
# renderer has stopped (a frozen frame never clips them).
ui_active="${dl}/ui-active"
ui_log="${dl}/ui-log"
ui_brand="${dl}/ui-brand"
ui_stopf="${dl}/ui-stop"
ui_notes="${dl}/ui-notes"
: > "$ui_log"
: > "$ui_brand"
: > "$ui_notes"
ui_pid=""
ui_step=""
ui_progress_path=""
ui_progress_total=""
ui_size() {
stty size < /dev/tty 2>/dev/null || true
}
if [ "$UI_ANIM" = 1 ]; then
ui_dims="$(ui_size)"
ui_rows="${ui_dims%% *}"
ui_cols="${ui_dims##* }"
case "$ui_cols" in ""|0|*[!0-9]*) ui_cols="${COLUMNS:-80}" ;; esac
case "$ui_rows" in ""|0|*[!0-9]*) ui_rows="${LINES:-24}" ;; esac
case "$ui_cols" in ""|*[!0-9]*) ui_cols=80 ;; esac
# The mark needs its indent + width (27 columns); the canvas spans the
# terminal (one column short of the edge, so a full row never wraps),
# capped at 120 columns.
ui_width=$((ui_cols - 1))
[ "$ui_width" -le 120 ] || ui_width=120
ui_banner=0
if [ "$UI_COLOR" = 1 ] && [ "$ui_width" -ge 40 ]; then ui_banner=1; fi
# The paths ride the environment, never -v (which rewrites backslashes)
# and never a command string.
PRIME_AGENT_UI_DIR="$dl" awk -v banner="$ui_banner" -v color="$UI_COLOR" \
-v width="$ui_width" -v height="$ui_rows" -v ppid="$$" "$banner_awk" >&2 &
ui_pid=$!
fi
# ui_stop: freeze the renderer on its last frame, then print the waiting
# warnings in full.
ui_stop() {
if [ -n "$ui_pid" ]; then
rm -f "$ui_active"
: > "$ui_stopf"
wait "$ui_pid" 2>/dev/null || true
ui_pid=""
if [ -s "$ui_notes" ]; then
printf '\n' >&2
cat "$ui_notes" >&2
: > "$ui_notes"
fi
fi
}
# ui_set_active <label> [detail]: the renderer's active row (written whole,
# then renamed, so a tick never reads half a file).
ui_set_active() {
printf '%s\n%s\n%s\n%s\n' "$1" "${2:-}" "$ui_progress_path" "$ui_progress_total" > "${ui_active}.tmp"
mv -f "${ui_active}.tmp" "$ui_active"
}
# A compact size: 19855079 -> "19.9 MB".
ui_mb() {
ui_tenths=$((($1 + 50000) / 100000))
printf '%d.%d MB' "$((ui_tenths / 10))" "$((ui_tenths % 10))"
}
# ui_line <text>: one finished line (the renderer's list, or stderr).
ui_line() {
if [ -n "$ui_pid" ]; then
printf '%s\n' "$1" >> "$ui_log"
else
printf '%s\n' "$1" >&2
fi
}
# title <version text>: the title line's version (the renderer shows the
# brand line from the start; captured output prints it once here).
title() {
if [ -n "$ui_pid" ]; then
printf '%s\n' "$1" > "$ui_brand"
else
printf ' %sInstalling PRIME Agent%s %s%s%s\n\n' "$C_BOLD" "$C_RESET" "$C_DIM" "$1" "$C_RESET" >&2
fi
}
# step_start <label>: the step is running (the spinner row on a terminal;
# nothing in captured output, where only the result line prints).
step_start() {
ui_step="$1"
if [ -n "$ui_pid" ]; then ui_set_active "$1"; fi
}
# step_detail <text>: the active step's current detail (the spinner row on
# a terminal; an indented line in captured output).
step_detail() {
if [ -n "$ui_pid" ]; then
ui_set_active "$ui_step" "$1"
else
printf ' %s\n' "$1" >&2
fi
}
step_end() {
ui_step=""
ui_progress_path=""
ui_progress_total=""
if [ -n "$ui_pid" ]; then rm -f "$ui_active"; fi
}
# step_ok <text> [detail]: the step's result line.
step_ok() {
step_end
ui_line " ${C_ACCENT}✓${C_RESET} $1${2:+ ${C_DIM}($2)${C_RESET}}"
}
# step_fail <text> [reason]: a failed step's result line.
step_fail() {
step_end
ui_line " ${C_WARN}✗ $1${2:+ ($2)}${C_RESET}"
}
# step_clear: the step finished with nothing worth a line.
step_clear() {
step_end
}
# note: a warning, in full, in amber; todo: the exact command that fixes
# it, uncolored so it copies cleanly. On a terminal both wait for the
# renderer to stop.
note() {
if [ -n "$ui_pid" ]; then
printf '%s%s%s\n' "$C_WARN" "$*" "$C_RESET" >> "$ui_notes"
else
printf '%s%s%s\n' "$C_WARN" "$*" "$C_RESET" >&2
fi
}
todo() {
if [ -n "$ui_pid" ]; then
printf ' %s\n' "$*" >> "$ui_notes"
else
printf ' %s\n' "$*" >&2
fi
}
dim() {
printf ' %s%s%s\n' "$C_DIM" "$*" "$C_RESET" >&2
}
die() {
if [ -n "$ui_step" ]; then step_fail "$ui_step"; fi
ui_stop
printf '%sinstall-rust.sh: %s%s\n' "$C_WARN" "$1" "$C_RESET" >&2
exit 1
}
# A path with the home directory spelled as ~ (display only).
tilde() {
case "$1" in
"$HOME"/*) printf '~%s' "${1#"$HOME"}" ;;
*) printf '%s' "$1" ;;
esac
}
ts_takeover_from=""
ts_takeover_undo=""
migrated_note=""
# The renderer always restores the cursor and line wrap when it stops; the
# trap stops it on every exit path (an INT/TERM exits through it too).
# The pre-flights' exits sit far from the run's own success-path sweep
# below, and a refused check dies before the full trap is armed — so with
# either check knob set this run's every exit also cleans the staging.
if [ "${PRIME_AGENT_ROLLBACK_CHECK:-}" = "1" ] || [ "${PRIME_AGENT_ARCHIVE_CHECK:-}" = "1" ]; then
# The stage rides too (an abort during the archive check's extraction
# must leave no staged tree under the prefix); `stage` is initialized
# before the traps, so the sweep targets only what THIS script assigns.
trap 'ui_stop; rm -rf "${dl:-}" "${stage:-}"' EXIT
else
trap 'ui_stop; rm -rf "$dl"' EXIT
fi
stage=""
publish_parked=""
# THE PUBLISH-WINDOW RESTORE (the interrupt handler's discipline, shared
# by the cleanup trap): the publish parks the incoming live tree at its
# rollback slot and only then moves the new stage in — between those two
# renames an interrupt would otherwise delete the staged payload (this
# run's own trash, the sweep's rule) while the parked tree stays aside,
# leaving share_dir with NOTHING live in it (the bots' finding: the
# machine's launcher breaks until a manual rollback). The restore mirrors
# the publish's own mv-failure branch: the parked tree goes back to the
# live path, and the generation record's entry for the vacated slot then
# simply names a path that no longer exists — the rollback's record read
# skips absent entries by design. Defined before the traps that call it;
# before the publish window it is a no-op (publish_parked stays empty).
publish_window_restore() {
# share_dir ABSENT is the window's own signature: once the new stage has
# landed there, the publish is done, the parked tree is exactly the
# rollback generation it should be, and no signal may un-publish it.
if [ -n "${publish_parked:-}" ] && [ -d "${publish_parked}" ] \
&& [ ! -e "${share_dir:-}" ]; then
if mv "${publish_parked}" "${share_dir}" 2>/dev/null; then
publish_parked=""
else
echo "warning: could not restore the previous prime-agent payload from ${publish_parked}; restore it with: mv '${publish_parked}' '${share_dir}'" >&2
fi
fi
}
ui_interrupted() {
# The failed-step line prints FIRST: it writes the renderer's files
# under the download staging, and removing that mid-write would fail
# the UI's own teardown. Then the interrupted install leaves nothing
# behind it would not own — the download staging always, and the
# extraction stage when THIS run created it (a rollback's stage is the
# KEPT generation itself, never this run's trash to delete; the guard
# matches the cleanup trap's). `stage` is INITIALIZED to empty above —
# before any trap can fire — so a caller-exported `stage` in this run's
# environment is never the removal's target.
if [ -n "$ui_step" ]; then step_fail "$ui_step" "interrupted"; fi
ui_stop
publish_window_restore
rm -rf "$dl"
if [ -z "${rollback_from:-}" ] && [ -n "${stage:-}" ]; then
rm -rf "$stage"
fi
}
trap 'ui_interrupted; exit 130' INT
trap 'ui_interrupted; exit 143' HUP TERM
# Every network read goes through fetch: a connect timeout, a whole-call
# cap, a stall cutoff (under 1 KB/s for 30s), and 3 attempts — a stalled
# connection fails with the URL named instead of hanging forever. The loop
# replaces curl's --retry-all-errors, which older curls (macOS) lack; a
# retry resumes the partial file (-C -) instead of starting over. The last
# curl error lands in fetch_error for the caller's message. The request
# and every redirect hop must be https, so an https base cannot hand the
# download to plaintext; PRIME_AGENT_ALLOW_HTTP=1 (the HTTPS rule's local
# channel knob) also allows http.
# Usage: fetch <url> <output file> <max seconds> [bar]
fetch() {
fetch_attempt=1
fetch_error=""
fetch_proto="=https"
if [ "${PRIME_AGENT_ALLOW_HTTP:-}" = "1" ]; then
fetch_proto="=http,https"
fi
rm -f "$2"
if [ "${4:-}" = bar ] && [ -n "$ui_pid" ]; then
ui_progress_total="$(curl -fsSIL --proto "$fetch_proto" --proto-redir "$fetch_proto" \
--connect-timeout 10 --max-time 15 "$1" 2>/dev/null \
| tr -d '\r' | awk 'tolower($1) == "content-length:" { size = $2 } END { print size }')"
case "$ui_progress_total" in ""|*[!0-9]*) ui_progress_total="" ;; esac
# The renderer reads the size through a fixed link in its own dir. Git
# Bash's default ln -s deep-copies and refuses a missing target, so
# there the step keeps its spinner without the bar.
if ln -sf "$2" "${dl}/ui-progress" 2>/dev/null; then
ui_progress_path="1"
fi
ui_set_active "$ui_step"
fi
while :; do
if curl -fsSL --proto "$fetch_proto" --proto-redir "$fetch_proto" \
-C - --connect-timeout 10 --max-time "$3" \
--speed-limit 1024 --speed-time 30 "$1" -o "$2" 2>"$2.err"; then
rm -f "$2.err"
return 0
fi
fetch_error="$(sed -n 's/^curl: ([0-9]*) //p' "$2.err" | tail -n 1)"
[ "$fetch_attempt" -lt 3 ] || return 1
fetch_attempt=$((fetch_attempt + 1))
if [ "${4:-}" = bar ]; then
step_detail "retrying (${fetch_attempt} of 3)${fetch_error:+: $fetch_error}"
fi
sleep 1
done
}
# --- platform detection ----------------------------------------------------
# uname -m maps directly to the built target: an Apple-Silicon Mac whose
# shell (and therefore binaries) run under Rosetta 2 reports x86_64 and
# gets the x86_64 build, which is the correct build for that runtime.
# Windows runs this script only from a POSIX shell (Git Bash / MSYS2 /
# Cygwin): uname -s reports MINGW*_NT-*, MSYS_NT-*, or CYGWIN_NT-*, and
# the x86_64 build is the MSVC target. The Windows-native route is
# install.ps1 (irm | iex); this arm keeps the sh one-liner working for
# Git Bash users. Every later section reads WINDOWS / BINARY_NAME (the
# path spellings, the payload check, the launcher, the takeover gates).
OS="$(uname -s)"
ARCH="$(uname -m)"
WINDOWS="no"
# CHANNEL_PLATFORM is the channel manifest's platform alias (the TS
# NATIVE_PLATFORMS spelling pa-core::update::install::current_platform_alias
# reads).
case "$OS:$ARCH" in
Darwin:arm64) CHANNEL_PLATFORM=darwin-arm64 ;;
Darwin:x86_64) CHANNEL_PLATFORM=darwin-x64 ;;
Linux:x86_64) CHANNEL_PLATFORM=linux-x64 ;;
Linux:aarch64) CHANNEL_PLATFORM=linux-arm64 ;;
MINGW64_NT*:x86_64|MINGW_NT*:x86_64|MSYS_NT*:x86_64|CYGWIN_NT*:x86_64)
CHANNEL_PLATFORM=win32-x64; WINDOWS=yes ;;
*)
die "no rust build is published for ${OS} ${ARCH} (detected via uname);
the release channel builds aarch64-apple-darwin, x86_64-apple-darwin,
aarch64-unknown-linux-gnu, x86_64-unknown-linux-gnu, and
x86_64-pc-windows-msvc (the Windows build installs through this script
under Git Bash/MSYS2/Cygwin — uname MINGW*_NT*/MSYS_NT*/CYGWIN_NT* — or
through install.ps1 in PowerShell)"
;;
esac
# The staged binary name: the MSVC build ships prime-agent.exe; the
# extraction check, the launcher, and the manifest row all name it.
if [ "$WINDOWS" = "yes" ]; then
BINARY_NAME="prime-agent.exe"
else
BINARY_NAME="prime-agent"
fi
# --- glibc floor (Linux) ------------------------------------------------------
# The continuous workflow builds the GNU/Linux targets inside an
# ubuntu:22.04 (glibc 2.35) container, so the published Linux binaries
# require glibc symbols no newer than 2.35. Refuse installs on older
# glibc (or non-glibc) systems up front with the exact floor instead of
# installing a payload the dynamic loader will refuse to start.
if [ "$OS" = "Linux" ]; then
ldd_line="$(ldd --version 2>&1 | head -n 1)"
case "$ldd_line" in
*musl*) die "musl libc is not supported: the Linux builds are GNU (glibc >= 2.35, Ubuntu 22.04 or newer) binaries" ;;
esac
glibc="${ldd_line##* }"
case "$glibc" in
[0-9]*.[0-9]*) ;;
*) die "could not determine the glibc version from: ${ldd_line}
the Linux builds require glibc >= 2.35 (Ubuntu 22.04 or newer)" ;;
esac
glibc_major="$(printf '%s' "${glibc%%.*}" | tr -cd '0-9')"
glibc_minor="$(printf '%s' "${glibc#*.}" | sed 's/\..*//' | tr -cd '0-9')"
if [ -z "$glibc_major" ] || [ -z "$glibc_minor" ] \
|| [ "$glibc_major" -lt 2 ] \
|| { [ "$glibc_major" -eq 2 ] && [ "$glibc_minor" -lt 35 ]; }; then
die "glibc ${glibc} is below the supported floor: the Linux builds are
compiled against glibc 2.35 (Ubuntu 22.04) and will not start here"
fi
say "glibc ${glibc} >= 2.35: supported"
fi
say "platform: ${CHANNEL_PLATFORM}"
# --- the R2 channel (the user path never touches GitHub) --------------------
# THE CHANNEL RESOLUTION (the TS install.sh parity): the channel pointer
# file gives the version, the channel manifest gives this platform's
# artifact row, and the versioned release prefix serves the tarball +
# SHA256SUMS. No gh, no GITHUB_TOKEN, no workflow-artifact API — the
# download base is the R2-backed domain and everything comes from it.
case "$CHANNEL" in
stable) CHANNEL_MANIFEST="latest.json" ;;
beta) CHANNEL_MANIFEST="beta.json" ;;
*) die "unknown release channel: ${CHANNEL} (stable or beta)" ;;
esac
# THE HTTPS RULE: a plaintext download base would let a network attacker
# swap the payload the checksum then "verifies" into place. The one escape
# hatch is the explicitly-named knob for a local channel or e2e run
# (install.ps1 carries the same rule + knob); it warns when it is active.
# The local modes (--rollback, --archive) download nothing, so the rule
# guards the channel install only.
if [ "$MODE" = channel ]; then
case "$BASE_URL" in
https://*) ;;
*)
if [ "${PRIME_AGENT_ALLOW_HTTP:-}" = "1" ]; then
note "! PRIME_AGENT_ALLOW_HTTP=1: the download base ${BASE_URL} is not https,"
note " so the download is plaintext. Use it only for a local channel you control."
else
die "the download base URL must be an https URL: ${BASE_URL}"
fi
;;
esac
fi
BASE_URL="${BASE_URL%/}"
# The channel pointer's one-line body (empty when the read fails).
read_channel_version() {
if fetch "${BASE_URL}/${CHANNEL}" "$dl/channel-pointer" 30; then
tr -d '[:space:]' < "$dl/channel-pointer"
fi
}
# The local modes (--rollback, --archive) already have their payload: the
# channel resolution here and the manifest, download, and checksum steps
# below run only for the channel install (the blocks are not re-indented).
# A rollback reads its version from the kept generation once the prefix is
# resolved (below the Python bootstrap).
if [ "$MODE" = channel ]; then
VERSION_PINNED="no"
if [ -n "${PRIME_AGENT_VERSION:-}" ]; then
VERSION="${PRIME_AGENT_VERSION#v}"
VERSION_PINNED="yes"
else
# THE RETRY (the publish's consistency window): the channel pointers
# flip one after the other (the manifest, then the version pointer), so
# a read landing between them sees the old pointer with the new
# manifest — a transient mismatch, not a broken channel. One re-read of
# the PAIR resolves it; a second refusal is a real error.
step_start "Checking the latest ${CHANNEL} version"
version_attempt=1
while :; do
VERSION="$(read_channel_version)"
[ -n "$VERSION" ] && break
version_attempt=$((version_attempt + 1))
[ "$version_attempt" -le 2 ] || break
sleep 1
done
fi
case "$VERSION" in
""|v)
die "could not resolve the latest ${CHANNEL} version from ${BASE_URL}/${CHANNEL}
(set PRIME_AGENT_VERSION to pin an exact version, or check the network)"
;;
*[!0-9A-Za-z.-]*)
die "invalid version from the ${CHANNEL} channel pointer: ${VERSION}"
;;
esac
step_clear
say "installing prime-agent ${VERSION} from the ${CHANNEL} channel (${CHANNEL_PLATFORM})"
title "${VERSION} (${CHANNEL})"
elif [ "$MODE" = archive ]; then
# --- --archive: a local release archive ------------------------------------------
# The archive must carry the channel naming for this platform; the version
# comes from the name. The channel download and its checksum checks are
# skipped: the operator named the payload (the tarball must still contain an
# executable payload binary, checked at extraction). On Windows a drive-letter
# path (the C:\... form `prime-agent update --archive` passes) goes to the
# POSIX form first: the name below splits on /, and tar reads C: as a host.
if [ "$WINDOWS" = "yes" ] && command -v cygpath >/dev/null 2>&1; then
archive_posix="$(cygpath -u "$ARCHIVE")" || die "could not resolve the archive path ${ARCHIVE}"
ARCHIVE="$archive_posix"
fi
[ -f "$ARCHIVE" ] || die "the release archive ${ARCHIVE} does not exist"
archive_name="${ARCHIVE##*/}"
case "$archive_name" in
prime-agent-?*-"${CHANNEL_PLATFORM}".tar.gz) ;;
*) die "${archive_name} is not a ${CHANNEL_PLATFORM} release archive (expected prime-agent-<version>-${CHANNEL_PLATFORM}.tar.gz)" ;;
esac
VERSION="${archive_name#prime-agent-}"
VERSION="${VERSION%-"${CHANNEL_PLATFORM}".tar.gz}"
# A leading v is the pin's accepted spelling too (`--rollback`'s marker
# versions carry none; the exact payload match below compares the bare
# version the binary reports).
VERSION="${VERSION#v}"
case "$VERSION" in
*[!0-9A-Za-z.-]*) die "invalid version in the archive name ${archive_name}: ${VERSION}" ;;
esac
asset="$ARCHIVE"
say "installing prime-agent ${VERSION} from the local archive ${ARCHIVE}"
title "${VERSION} (local archive)"
step_ok "Using the local archive" "$(tilde "$ARCHIVE")"
fi
# --- the Python bootstrap: the installer must not depend on system python3 ----
# Every scripting step below (the store guard's realpath, the artifact's
# JSON parsing and zip extraction, the daemon probe) needs a Python — and a
# fresh machine may have none. The fix is uv first: a single static binary
# whose installer needs only curl + sh, and uv can then provide the Python
# itself (its own standalone builds — no system python anywhere).
#
# NOTE ON THE GUARD ORDER BELOW: the astral installer writes only its own
# fixed install path (~/.local/bin/uv), never under this installer's
# prefix — so the store guard still runs before the FIRST PREFIX-DERIVED
# write, which is the invariant that matters. THE STORE-ALIAS FALLBACK:
# ~/.local/bin can still resolve INSIDE the shared session store (the
# alias shape: a user symlinked ~/.local into ~/.prime/agent), which
# would put the astral installer's write under the store before the
# guard runs — so when the default target resolves there, uv goes to
# THIS install's prefix bin dir instead (the payload-adjacent fallback)
# and the store is never written. (uv's install otherwise lands on PATH
# at ~/.local/bin, the same default prefix this script uses; a custom
# prefix simply keeps uv at ~/.local, where the product's own ensure_uv
# also looks for it.)
# The physical-path probe is POSIX-only (cd + pwd -P): readlink -f is
# coreutils, and macOS ships without it. A DANGLING target (a uv target
# directory that does not exist yet - the normal shape at install time)
# must still resolve through its nearest EXISTING ancestor: the old
# single-level probe returned the unresolved spelling, and a parent
# symlink into the shared store would slip the containment check (the
# bots' finding) - the uv binary would then be created THROUGH the
# symlink, inside the store. The parent/base split rides parameter
# expansion alone (no dirname/basename: the bare-machine PATH of the
# installer's own support matrix carries neither).
physical_path() {
# Trailing slashes normalize first (a PREFIX spelled with one must not
# abort the ancestor walk): "/x/" resolves like "/x", never as an
# empty-basename dead end.
phys_input="$1"
while [ "$phys_input" != "/" ] && [ "$phys_input" != "${phys_input%/}" ]; do
phys_input="${phys_input%/}"
done
case "$phys_input" in
*/*) phys_parent="${phys_input%/*}" phys_base="${phys_input##*/}" ;;
*) phys_parent="." phys_base="$phys_input" ;;
esac
if [ -d "$phys_input" ]; then
( cd "$phys_input" 2>/dev/null && pwd -P ) || printf '%s' "$phys_input"
elif [ -z "$phys_base" ] || [ "$phys_parent" = "$phys_input" ]; then
printf '%s' "$phys_input"
else